Login with LinkedIn in CodeIgniter


Login with LinkedIn feature makes web login system completed. It provides an easy and quick way to sign in to the web application without creating an account on that web application. Using LinkedIn login, the users can log into your website with their LinkedIn account without register in your website. Our earlier tutorial showed you the integration of LinkedIn login in PHP. In this tutorial, we will show you how to integrate LinkedIn login system in CodeIgniter.

Before you get started to implement LinkedIn login in CodeIgniter 3 using OAuth Client Library, create a LinkedIn app in LinkedIn Developer Network panel and get the API Key (Client ID) and API Secret (Client Secret). You should need to set Authorized Redirect URLs that would be the same of user authentication controller URL (http://localhost/codeigniter/user_authentication/). Also, need to specify the Redirect URL, API Key, and API Secret in your script at the time of connecting with LinkedIn API.

Once your LinkedIn app creation is completed, copy the Client ID and Client Secret and put them into the respective variable in the script.

Take a look at the files structure of Login with LinkedIn in CodeIgniter using PHP client library.

codeigniter-linkedin-login-files-structure

Database Table Creation

To store the LinkedIn profile information, you need to create a table into the database. The following SQL creates a users table with some required fields in MySQL database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `oauth_uid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `gender` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `picture_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `profile_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Config

autoload.php:
The database and session libraries are needed throughout the login process. It will be a good idea to specify these libraries in the autoload.php file.

$autoload['libraries'] = array('session','database');

linkedin.php:
LinkedIn API Configuration variables are defined in this file. You need to specify the Client Id (linkedin_api_key), Client Secret (linkedin_api_secret) and redirect URL (linkedin_redirect_url) according to your LinkedIn App credentials.

<?php defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
|  LinkedIn API Configuration
| -------------------------------------------------------------------
|
| To get an facebook app details you have to create a Facebook app
| at Facebook developers panel (https://developers.facebook.com)
|
|  linkedin_api_key        string   Your LinkedIn App Client ID.
|  linkedin_api_secret     string   Your LinkedIn App Client Secret.
|  linkedin_redirect_url   string   URL to redirect back to after login. (do not include base URL)
|  linkedin_scope          array    Your required permissions.
*/
$config['linkedin_api_key']       = 'InsertAppClientId';
$config['linkedin_api_secret']    = 'InsertAppClientSecret';
$config['linkedin_redirect_url']  = 'user_authentication/';
$config['linkedin_scope']         = 'r_basicprofile r_emailaddress';

Controllers (User_authentication.php)

User_Authentication controller contains three functions, __construct(), index(), and logout().

  • __construct() – The LinkedIn API config file and User model are loaded in this method.
  • index() – The following functionalities are implemented in this method.
    • Connect with LinkedIn API using the LinkedIn client library, pass the user profile information to the User model for insert into the database.
    • Pass the user data to the view and load the profile details view for authenticated user.
    • Load the login view for the non-authenticated user.
  • logout() – This method removes the OAuth status and user data from session and logs out the user from their LinkedIn account.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class 
User_Authentication extends CI_Controller
{
    function 
__construct() {
        
parent::__construct();
        
        
// Load linkedin config
        
$this->load->config('linkedin');
        
        
//Load user model
        
$this->load->model('user');
    }
    
    public function 
index(){
        
$userData = array();
        
        
//Include the linkedin api php libraries
        
include_once APPPATH."libraries/linkedin-oauth-client/http.php";
        include_once 
APPPATH."libraries/linkedin-oauth-client/oauth_client.php";
        
        
        
//Get status and user info from session
        
$oauthStatus $this->session->userdata('oauth_status');
        
$sessUserData $this->session->userdata('userData');
        
        if(isset(
$oauthStatus) && $oauthStatus == 'verified'){
            
//User info from session
            
$userData $sessUserData;
        }elseif((isset(
$_REQUEST["oauth_init"]) && $_REQUEST["oauth_init"] == 1) || (isset($_REQUEST['oauth_token']) && isset($_REQUEST['oauth_verifier']))){
            
$client = new oauth_client_class;
            
$client->client_id $this->config->item('linkedin_api_key');
            
$client->client_secret $this->config->item('linkedin_api_secret');
            
$client->redirect_uri base_url().$this->config->item('linkedin_redirect_url');
            
$client->scope $this->config->item('linkedin_scope');
            
$client->debug false;
            
$client->debug_http true;
            
$application_line __LINE__;
            
            
//If authentication returns success
            
if($success $client->Initialize()){
                if((
$success $client->Process())){
                    if(
strlen($client->authorization_error)){
                        
$client->error $client->authorization_error;
                        
$success false;
                    }elseif(
strlen($client->access_token)){
                        
$success $client->CallAPI('http://api.linkedin.com/v1/people/~:(id,email-address,first-name,last-name,location,picture-url,public-profile-url,formatted-name)'
                        
'GET',
                        array(
'format'=>'json'),
                        array(
'FailOnAccessError'=>true), $userInfo);
                    }
                }
                
$success $client->Finalize($success);
            }
            
            if(
$client->exit) exit;
    
            if(
$success){
                
//Preparing data for database insertion
                
$first_name = !empty($userInfo->firstName)?$userInfo->firstName:'';
                
$last_name = !empty($userInfo->lastName)?$userInfo->lastName:'';
                
$userData = array(
                    
'oauth_provider'=> 'linkedin',
                    
'oauth_uid'     => $userInfo->id,
                    
'first_name'     => $first_name,
                    
'last_name'     => $last_name,
                    
'email'         => $userInfo->emailAddress,
                    
'locale'         => $userInfo->location->name,
                    
'profile_url'     => $userInfo->publicProfileUrl,
                    
'picture_url'     => $userInfo->pictureUrl
                
);
                
                
//Insert or update user data
                
$userID $this->user->checkUser($userData);
                
                
//Store status and user profile info into session
                
$this->session->set_userdata('oauth_status','verified');
                
$this->session->set_userdata('userData',$userData);
                
                
//Redirect the user back to the same page
                
redirect('/user_authentication');

            }else{
                 
$data['error_msg'] = 'Some problem occurred, please try again later!';
            }
        }elseif(isset(
$_REQUEST["oauth_problem"]) && $_REQUEST["oauth_problem"] <> ""){
            
$data['error_msg'] = $_GET["oauth_problem"];
        }else{
            
$data['oauthURL'] = base_url().$this->config->item('linkedin_redirect_url').'?oauth_init=1';
        }
        
        
$data['userData'] = $userData;
        
        
// Load login & profile view
        
$this->load->view('user_authentication/index',$data);
    }

    public function 
logout() {
        
//Unset token and user data from session
        
$this->session->unset_userdata('oauth_status');
        
$this->session->unset_userdata('userData');
        
        
//Destroy entire session
        
$this->session->sess_destroy();
        
        
// Redirect to login page
        
redirect('/user_authentication');
    }
}

Libraries

LinkedIn OAuth client library is used to connect with the LinkedIn API and integrate login system with LinkedIn. The linkedin-oauth-client/ directory contains the required PHP client libraries for authentication.

Models (User.php)

The checkUser() method of User model used to insert or update the user profile information into the database.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class 
User extends CI_Model{
    function 
__construct() {
        
$this->tableName 'users';
        
$this->primaryKey 'id';
    }
    public function 
checkUser($data = array()){
        
$this->db->select($this->primaryKey);
        
$this->db->from($this->tableName);
        
$this->db->where(array('oauth_provider'=>$data['oauth_provider'],'oauth_uid'=>$data['oauth_uid']));
        
$prevQuery $this->db->get();
        
$prevCheck $prevQuery->num_rows();
        
        if(
$prevCheck 0){
            
$prevResult $prevQuery->row_array();
            
$data['modified'] = date("Y-m-d H:i:s");
            
$update $this->db->update($this->tableName,$data,array('id'=>$prevResult['id']));
            
$userID $prevResult['id'];
        }else{
            
$data['created'] = date("Y-m-d H:i:s");
            
$data['modified'] = date("Y-m-d H:i:s");
            
$insert $this->db->insert($this->tableName,$data);
            
$userID $this->db->insert_id();
        }

        return 
$userID?$userID:FALSE;
    }
}

Views (user_authentication/index.php)

If the user already logged in with their LinkedIn account, the profile details will be shown, otherwise, Sign in with LinkedIn button will be displayed.

<?php
if(!empty($error_msg)){
    echo 
'<p class="error">'.$error_msg.'</p>';    
}

if(!empty(
$userData)){ ?> <div class="login-form"> <div class="head"> <img src="<?php echo $userData['picture_url']; ?>" alt=""/> </div> <div class="content"> <li> <p><?php echo $userData['first_name'].' '.$userData['last_name']; ?></p> </li> <li> <p><?php echo $userData['email']; ?></p> </li> <li> <p><?php echo $userData['locale']; ?></p> </li> <div class="foot"> <a href="<?php echo base_url().'user_authentication/logout'?>">Logout</a> <a href="<?php echo $userData['profile_url']; ?>" target="_blank">View Profile</a> <div class="clear"> </div> </div> </div> </div> <?php
}else{
    echo 
'<div class="linkedin_btn"><a href="'.$oauthURL.'"><img src="'.base_url().'assets/images/sign-in-with-linkedin.png" /></a></div>';
}
?>

Conclusion

That’s enough! Now run the application authentication URL (http://localhost/codeigniter/user_authentication/) on the browser and check the login with LinkedIn in CodeIgniter. All files including LinkedIn OAuth Client Library are included into the Source Code package, download it and place the files into the CodeIgniter application.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

10 Comments

  1. Shivaji Said...
  2. Vinil Lakkavatri Said...
  3. Asher Said...
  4. Asher Said...
  5. Asher Said...
    • CodexWorld Said...
  6. Rohan Kamble Said...
    • CodexWorld Said...
  7. Ketan Talaviya Said...
  8. KEtan TAlaviya Said...

Leave a reply