Login with LinkedIn in CodeIgniter

Login with LinkedIn feature adds extra value for the social login system on the web application. 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 on your website. The LinkedIn login can be easily integrated using PHP OAuth client on the website. In our previous LinkedIn API tutorial, we have shown you a simple way to integrate LinkedIn login in PHP.

If your web application built with CodeIgniter framework, LinkedIn OAuth library needs to be integrated into CodeIgniter. In this tutorial, we will show you how to integrate LinkedIn login system in CodeIgniter and store the LinkedIn profile information in the MySQL database. We will use OAuth 2.0 and LinkedIn login API v2 to build LinkedIn login script with CodeIgniter.

Before getting started to integrate Sign In with LinkedIn in CodeIgniter, take a look at the files structure.

codeigniter_linkedin_login/
├── application/
│   ├── controllers/
│   │   └── User_authentication.php
│   ├── libraries/
│   │   └── Linkedin.php
│   ├── models/
│   │   └── User.php
│   ├── third_party/
│   │   └── linkedin-oauth-client/
│   └── views/
│       └── user_authentication/
│           └── index.php
└── assets/
    ├── css/
    │   └── style.css
    └── images/
        └── linkedin-sign-in-btn.png

Create LinkedIn App

Client ID and Client Secret are required to access the LinkedIn API from the web application. To generate a Client ID and Secret, create an App on LinkedIn Developers panel.

  • Go to the LinkedIn Developers page and login with your LinkedIn account credentials.
  • Click the Create app button.
  • Provide the required information about your app and click Create app.
  • In the App settings screen, switch to the Auth tab » Scroll down to OAuth 2.0 settings section.
    • Specify the Callback URL in the Redirect URLs fields and Update the App settings.
  • In the Application credentials section, you will see the Client ID and Client Secret. These App credentials (App ID and Secret) need to be specified in the script at the time of connecting to the LinkedIn API.
    linkedin-php-oauth-api-create-app-client-id-secret-codexworld

Create Database Table

To store the LinkedIn profile information, a table needs to be created in the database. The following SQL creates a users table with some basic fields in the MySQL database to hold the LinkedIn account data.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` enum('linkedin','google','facebook','twitter') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'linkedin',
 `oauth_uid` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
 `gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
 `locale` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
 `picture` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
 `link` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Config

autoload.php
In the config/autoload.php file, define the commonly used helper (url) and library (database and session) to load automatically on every request.

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

linkedin.php
In the config/linkedin.php file, the LinkedIn API configurations are defined. Specify the Client ID, Client Secret and Redirect URL according to your LinkedIn App credentials.

defined('BASEPATH') OR exit('No direct script access allowed'); 
/* 
| ------------------------------------------------------------------- 
|  LinkedIn API Configuration 
| ------------------------------------------------------------------- 
| 
| To get an LinkedIn app details you have to create a LinkedIn app 
| at LinkedIn Developers panel (https://www.linkedin.com/developers/) 
| 
|  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 API permissions. 
*/ 
$config['linkedin_api_key']       = 'Insert_LinkedIn_App_ID'; 
$config['linkedin_api_secret']    = 'Insert_LinkedIn_App_Secret'; 
$config['linkedin_redirect_url']  = 'user_authentication/'; 
$config['linkedin_scope']         = 'r_liteprofile r_emailaddress';

Note that: You’ll find the Client ID and Secret from your LinkedIn App settings page.

Third Party

linkedin-oauth-client/
LinkedIn OAuth 2.0 Client library is used to connect and authenticate with LinkedIn API v2. The linkedin-oauth-client library needs to be placed in the third_party/ directory of your CodeIgniter application.

Note that: You don’t need to download the LinkedIn OAuth client library separately, all the required files are included in the source code.

Libraries

Linkedin.php
The LinkedIn library helps to integrate LinkedIn OAuth 2.0 in CodeIgniter 3.x application. Using this LinkedIn class, you can easily add the LinkedIn login functionality in the CodeIgniter application with OAuth 2.0 and Linkedin API v2.

Note that: You don’t need to download the LinkedIn OAuth client library separately, all the required files are included in the source code.

Controllers (User_authentication.php)

The User_Authentication controller handles the LinkedIn API authentication process using PHP OAuth Client library.

  • __construct() – Loads the LinkedIn library and User model to handle the OAuth and database related works.
  • index()
    • Initially, the authentication URL is generated for login.
    • If the user already authenticated with the LinkedIn account, the account information is retrieved from the session.
    • Otherwise,
      • The authenticate() method of the LinkedIn library is used to authenticate with the LinkedIn API.
      • The getUserInfo() method of the LinkedIn library is used to fetch the account information from the LinkedIn account.
      • Insert LinkedIn account data in the database using checkUser() function of the User model.
      • Store the auth status and user profile info in the SESSION.
  • Pass the user’s account data (for authenticated user) or OAuth URL (for non-authenticated user) to the view.
  • logout() – If the user wishes to log out from their LinkedIn account,
    • Remove auth status and user data from the SESSION.
    • Redirect the user to the social login page.
<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 
 
class User_Authentication extends CI_Controller 
{ 
    function __construct() { 
        parent::__construct(); 
         
        // Load linkedin oauth library 
        $this->load->library('linkedin'); 
         
        //Load user model 
        $this->load->model('user'); 
    } 
     
    public function index(){ 
        $userData = array(); 
         
        // Get status and user info from session 
        $oauthStatus $this->session->userdata('oauth_status'); 
        $sessUserData $this->session->userdata('userData'); 
         
        if(isset($oauthStatus) && $oauthStatus == 'verified'){ 
            // Get the user info from session 
            $userData $sessUserData; 
        }elseif((isset($_GET["oauth_init"]) && $_GET["oauth_init"] == 1) || (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) || (isset($_GET['code']) && isset($_GET['state']))){ 
             
            // Authenticate with LinkedIn 
            if($this->linkedin->authenticate()){ 
                 
                // Get the user account info 
                $userInfo $this->linkedin->getUserInfo(); 
                 
                // Preparing data for database insertion 
                $userData = array(); 
                $userData['oauth_uid']  = !empty($userInfo['account']->id)?$userInfo['account']->id:''; 
                $userData['first_name'] = !empty($userInfo['account']->firstName->localized->en_US)?$userInfo['account']->firstName->localized->en_US:''; 
                $userData['last_name']  = !empty($userInfo['account']->lastName->localized->en_US)?$userInfo['account']->lastName->localized->en_US:''; 
                $userData['email']      = !empty($userInfo['email']->elements[0]->{'handle~'}->emailAddress)?$userInfo['email']->elements[0]->{'handle~'}->emailAddress:''; 
                $userData['picture']    = !empty($userInfo['account']->profilePicture->{'displayImage~'}->elements[0]->identifiers[0]->identifier)?$userInfo['account']->profilePicture->{'displayImage~'}->elements[0]->identifiers[0]->identifier:''; 
                $userData['link']       = 'https://www.linkedin.com/'; 
         
                // Insert or update user data to the database 
                $userData['oauth_provider'] = 'linkedin'; 
                $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'] = 'Error connecting to LinkedIn! try again later! <br/>'.$this->linkedin->client->error; 
            } 
        }elseif(isset($_REQUEST["oauth_problem"]) && $_REQUEST["oauth_problem"] <> ""){ 
            $data['error_msg'] = $_GET["oauth_problem"]; 
        } 
         
        $data['userData'] = $userData; 
        $data['oauthURL'] = base_url().$this->config->item('linkedin_redirect_url').'?oauth_init=1'; 
         
        // 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'); 
    } 
}

Models (User.php)

The User model handles the database related operations (insert and update).

  • __construct() – Define the database table name.
  • checkUser() – Insert or update the LinkedIn profile information based on the OAuth provider and ID. Returns the row ID on success, and FALSE on error.
<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 
 
class User extends CI_Model { 
    function __construct() { 
        $this->tableName 'users'; 
        $this->primaryKey 'id'; 
    } 
     
    /* 
     * Insert / Update linkedin profile data into the database 
     * @param array the data for inserting into the table 
     */ 
    public function checkUser($userData = array()){ 
        if(!empty($userData)){ 
            //check whether user data already exists in database with same oauth info 
            $this->db->select($this->primaryKey); 
            $this->db->from($this->tableName); 
            $this->db->where(array('oauth_provider'=>$userData['oauth_provider'], 'oauth_uid'=>$userData['oauth_uid'])); 
            $prevQuery $this->db->get(); 
            $prevCheck $prevQuery->num_rows(); 
             
            if($prevCheck 0){ 
                $prevResult $prevQuery->row_array(); 
                 
                //update user data 
                $userData['modified'] = date("Y-m-d H:i:s"); 
                $update $this->db->update($this->tableName$userData, array('id' => $prevResult['id'])); 
                 
                //get user ID 
                $userID $prevResult['id']; 
            }else{ 
                //insert user data 
                $userData['created']  = date("Y-m-d H:i:s"); 
                $userData['modified'] = date("Y-m-d H:i:s"); 
                $insert $this->db->insert($this->tableName$userData); 
                 
                //get user ID 
                $userID $this->db->insert_id(); 
            } 
        } 
         
        //return user ID 
        return $userID?$userID:FALSE; 
    } 
}

Views

user_authentication/index.php
If the user already logged in with their LinkedIn account, the profile details (ID, Picture, Name, Email, Profile Linke, etc) are displayed. Otherwise, Sign-in with LinkedIn button is shown to the user.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Login with LinkedIn in CodeIgniter by CodexWorld</title>

    <!-- Include stylesheet file -->
    <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/style.css"/>
</head>
<body>
<div class="container">
    <div class="in-box">
        <?php 
        if(!empty($error_msg)){ 
            echo '<p class="error">'.$error_msg.'</p>';     
        }
		
        if(!empty($userData)){ ?>
            <h2>LinkedIn Profile Details</h2>
            <div class="ac-data">
                <img src="<?php echo $userData['picture']; ?>"/>
                <p><b>LinkedIn ID:</b> <?php echo $userData['oauth_uid']; ?></p>
                <p><b>Name:</b> <?php echo $userData['first_name'].' '.$userData['last_name']; ?></p>
                <p><b>Email:</b> <?php echo $userData['email']; ?></p>
                <p><b>Logged in with:</b> LinkedIn</p>
                <p><b>Profile Link:</b> <a href="<?php echo $userData['link']; ?>" target="_blank">Click to visit LinkedIn page</a></p>
                <p><b>Logout from</b> <a href="<?php echo base_url().'user_authentication/logout'?>">LinkedIn</a></p>
            </div>
        <?php 
        }else{ 
            // Render LinkedIn login button 
            echo '<a href="'.$oauthURL.'"><img src="'.base_url().'assets/images/linkedin-sign-in-btn.png"></a>'; 
        } 
        ?>
    </div>
</div>
</body>
</html>

Test the LinkedIn Login in Codeigniter

To check the LinkedIn login in CodeIgniter application, open the application’s OAuth URL (https://www.example.com/user_authentication/) in the browser.

  • The Sign-In with LinkedIn button will appear, click on it.
  • You will be redirected to the LinkedIn OAuth dialog for Authentication.
  • After successful authentication, you will be redirected back to the web application and the LinkedIn account details will be displayed on the web page.
  • Also, LinkedIn profile data will be stored in the MySQL database.

Login with Facebook in CodeIgniter

Conclusion

Hope our LinkedIn login script helps you to implement the LinkedIn login in CodeIgniter. Also, you can use this script to migrate the old LinkedIn OAuth code with the latest LinkedIn API v2 and OAuth 2.0. If you want to make the LinkedIn login user-friendly, use JavaScript SDK to integrate LinkedIn Login without page refresh using JavaScript.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

11 Comments

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

Leave a reply

keyboard_double_arrow_up