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
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.
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;
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.
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.
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.
The User_Authentication controller handles the LinkedIn API authentication process using PHP OAuth Client library.
authenticate()
method of the LinkedIn library is used to authenticate with the LinkedIn API.getUserInfo()
method of the LinkedIn library is used to fetch the account information from the LinkedIn account.checkUser()
function of the User model.<?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'); } }
The User model handles the database related operations (insert and update).
<?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; } }
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>
To check the LinkedIn login in CodeIgniter application, open the application’s OAuth URL (https://www.example.com/user_authentication/
) in the browser.
Login with Facebook in CodeIgniter
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
Where do I get the linkedin library? You loaded a library “$this->load->library(‘linkedin’);” but where is the code or how to install them in my code!
i work on codeigniter 2.1.1 because my site is old so in this version is not made linkdedin sessions but i check on 3.0.3 version its working fine,u have any idea why..!
Hi ,
May I know how to post or share content through the same API.
Or may I get any demo code so that I can integrate with the same?
It would be grateful if you suggest or help in it?
Thanks,
Vinil Lakkavatri
i solved the problem in codeigniter 2.1,i change $config[‘sess_use_database’] = False; in config.php
i work on codeigniter 2.1.1 because my site is old so in this version is not made linkdedin sessions but i check on 3.0.3 version its working fine,u have any idea why..!
the code work correctly but problem is that after insertion i made few sessions like firstname,lastname,email,id ,but this sessions not made, is there ssl certification problem for saving sessions.i hope u understand bcoz my english is not good
No, SSL certificate is not required to store value in SESSION.
Hi there great content. It is of great help but just wanted to know where can I get linkedin-oauth-client ?
You can get all the required files including linkedin-oauth-client in the source code package.
This code is work properly.
Thank you very much to publish this blog.