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.


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` (
 `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,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


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 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');
User_Authentication extends CI_Controller
__construct() {
// Load linkedin config
//Load user model
    public function 
$userData = array();
//Include the linkedin api php libraries
include_once APPPATH."libraries/linkedin-oauth-client/http.php";
//Get status and user info from session
$oauthStatus $this->session->userdata('oauth_status');
$sessUserData $this->session->userdata('userData');
$oauthStatus) && $oauthStatus == 'verified'){
//User info from session
$userData $sessUserData;
$_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()){
$success $client->Process())){
$client->error $client->authorization_error;
$success false;
$success $client->CallAPI('http://api.linkedin.com/v1/people/~:(id,email-address,first-name,last-name,location,picture-url,public-profile-url,formatted-name)'
'FailOnAccessError'=>true), $userInfo);
$success $client->Finalize($success);
$client->exit) exit;
//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
//Redirect the user back to the same page

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

    public function 
logout() {
//Unset token and user data from session
//Destroy entire session
// Redirect to login page


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');
User extends CI_Model{
__construct() {
$this->tableName 'users';
$this->primaryKey 'id';
    public function 
checkUser($data = array()){
$prevQuery $this->db->get();
$prevCheck $prevQuery->num_rows();
$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'];
$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();


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.

'<p class="error">'.$error_msg.'</p>';    

$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
'<div class="linkedin_btn"><a href="'.$oauthURL.'"><img src="'.base_url().'assets/images/sign-in-with-linkedin.png" /></a></div>';


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


  1. Ketan Talaviya Said...
  2. KEtan TAlaviya Said...

Leave a reply