Skip to main content

Login with LinkedIn using PHP

Linkedin is one of the most popular social networks with the huge user base. Like the Facebook, Twitter and Google authentication, LinkedIn also is used for the user authentication in the website. If you want to allow your website’s user to login with the social account, LinkedIn login needs to be added. LinkedIn provides various API to integrate user login system in the website. Using LinkedIn API you can let the user login to your website with their LinkedIn account.
In this tutorial, we will show you how to integrate user Login System with LinkedIn using PHP. The login with LinkedIn feature helps the user to sign into your website with their LinkedIn account without registration on your website. Our LinkedIn login API tutorial provides you an easy way to build user login system with LinkedIn using PHP and store the user profile data into the MySQL database. We’ll use OAuth library to connect with LinkedIn and build LinkedIn login system in PHP.
Before you get started to integrate Login with LinkedIn using PHP, take a look at the files and folders structure.
  • src/
    • http.php
    • oauth_client.php
  • User.class.php
  • inConfig.php
  • index.php
  • logout.php
  • css/
  • images/

LinkedIn App Creation

  • Go to the Apps page at LinkedIn Developer Network and log in with your LinkedIn account credentials.
  • Click on the Add New Application link to creates new App.
  • Enter the new application details into the app registration form.
    • Company Info: If you have not already created a company page, select New Company and enter your company name.
    • Application Info: Enter all the application details and select Live option as Live Status.
    • Contact Info: Enter your contact details.
    • OAuth User Agreement: Select the Default Scope and enter Redirect URLs (http://localhost/linkedin_login_php/), Accept Redirect URL (http://localhost/linkedin_login_php/), Cancel Redirect URL (http://localhost/linkedin_login_php/).
    • Select the LinkedIn API Terms of Use checkbox.
  • Click on the Add Application button.
  • Once the application is created successfully, application details would be displayed.

Copy and keep the Client ID and Client Secret for later use.
For step-by-step guide to creating a LinkedIn App, see this tutorial – How to Create LinkedIn App, Client ID, and Client Secret

Database Table Creation

To store the user information from the LinkedIn database, a table (users) need to be created in MySQL database. At first, create a database (like codexworld) and run the below SQL on the database. The following SQL creates a users table with some basic fields in the database to hold the LinkedIn profile information.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` enum('','facebook','google','twitter','linkedin') COLLATE utf8_unicode_ci NOT NULL,
 `oauth_uid` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `gender` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `locale` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `link` 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;

LinkedIn OAuth Library for PHP

The src/ directory contains the LinkedIn OAuth client library for PHP. You don’t need to download it separately, all the required files are included in our source code.

User Class (User.class.php)

The User class helps to insert or update user data to the database using PHP and MySQL. In User.class.php file, you only need to specify your MySQL database credentials ($dbHost, $dbUsername, $dbPassword, and $dbName) and table name ($userTbl) where you want to store the user’s LinkedIn profile information.

<?php
class User {
    private $dbHost     = "localhost";
    private $dbUsername = "root";
    private $dbPassword = "*****";
    private $dbName     = "codexworld";
    private $userTbl    = 'users';
    
    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
    
    function checkUser($userData = array()){
        if(!empty($userData)){
            //Check whether user data already exists in database
            $prevQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
            $prevResult = $this->db->query($prevQuery);
            if($prevResult->num_rows > 0){
                //Update user data if already exists
                $query = "UPDATE ".$this->userTbl." SET first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
                $update = $this->db->query($query);
            }else{
                //Insert user data
                $query = "INSERT INTO ".$this->userTbl." SET oauth_provider = '".$userData['oauth_provider']."', oauth_uid = '".$userData['oauth_uid']."', first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
                $insert = $this->db->query($query);
            }
            
            //Get user data from the database
            $result = $this->db->query($prevQuery);
            $userData = $result->fetch_assoc();
        }
        
        //Return user data
        return $userData;
    }
}
?>

LinkedIn API Configuration (inConfig.php)

In inConfig.php file, specify your LinkedIn Client ID ($apiKey), Client Secret ($apiSecret), Callback URL ($redirectURL), and Permissions ($scope) to connect with LinkedIn API and working with OAuth library.

<?php
//Include LinkedIn client library 
require_once 'src/http.php';
require_once 'src/oauth_client.php';

/*
 * Configuration and setup LinkedIn API
 */
$apiKey     = 'InsertClientID';
$apiSecret  = 'InsertClientSecret';
$redirectURL= 'http://localhost/linkedin_login_php/';
$scope      = 'r_basicprofile r_emailaddress'; //API permissions
?>
Note that: You’ll find the Client ID and Client Secret on your LinkedIn Apps Authentication page.

Login & Get Profile Information (index.php)

Initially, the Sign in with LinkedIn button will be shown. Once the user authenticates with their LinkedIn account, the profile information will be fetched and pass to the User class for inserting into the MySQL database. Also, the LinkedIn profile details with logout button will be shown to the user.

<?php
//start session
if(!session_id()){
    session_start();
}

//Include Twitter config file && User class
include_once 'inConfig.php';
include_once 'User.class.php';

$authUrl = $output = '';

//If user already verified 
if(isset($_SESSION['oauth_status']) && $_SESSION['oauth_status'] == 'verified' && !empty($_SESSION['userData'])){
    //Prepare output to show to the user
    $userInfo = $_SESSION['userData'];
    $output = '<div class="login-form">
        <div class="head">
            <img src="'.$userInfo['picture'].'" alt=""/>
        </div>
        <form>
        <li>
            <p>'.$userInfo['first_name'].' '.$userInfo['last_name'].'</p>
        </li>
        <li>
            <p>'.$userInfo['email'].'</p>
        </li>
        <li>
            <p>'.$userInfo['locale'].'</p>
        </li>
        <div class="foot">
            <a href="logout.php">Logout</a>
            <a href="'.$userInfo['link'].'" target="_blank">View Profile</a>
            <div class="clear"> </div>
        </div>
        </form>
    </div>';
}elseif((isset($_GET["oauth_init"]) && $_GET["oauth_init"] == 1) || (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier']))){
    $client = new oauth_client_class;
    
    $client->client_id = $apiKey;
    $client->client_secret = $apiSecret;
    $client->redirect_uri = $redirectURL;
    $client->scope = $scope;
    $client->debug = false;
    $client->debug_http = true;
    $application_line = __LINE__;
    
    if(strlen($client->client_id) == 0 || strlen($client->client_secret) == 0){
        die('Please go to LinkedIn Apps page https://www.linkedin.com/secure/developer?newapp= , '.
            'create an application, and in the line '.$application_line.
            ' set the client_id to Consumer key and client_secret with Consumer secret. '.
            'The Callback URL must be '.$client->redirect_uri.'. Make sure you enable the '.
            'necessary permissions to execute the API calls your application needs.');
    }
    
    //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){
        //Initialize User class
        $user = new User();
        
        //Insert or update user data to the database
        $fname = $userInfo->firstName;
        $lname = $userInfo->lastName;
        $inUserData = array(
            'oauth_provider'=> 'linkedin',
            'oauth_uid'     => $userInfo->id,
            'first_name'    => $fname,
            'last_name'     => $lname,
            'email'         => $userInfo->emailAddress,
            'gender'        => '',
            'locale'        => $userInfo->location->name,
            'picture'       => $userInfo->pictureUrl,
            'link'          => $userInfo->publicProfileUrl,
            'username'      => ''
        );
        
        $userData = $user->checkUser($inUserData);
        
        //Storing user data into session
        $_SESSION['userData'] = $userData;
        $_SESSION['oauth_status'] = 'verified';
        
        //Redirect the user back to the same page
        header('Location: ./');
    }else{
         $output = '<h3 style="color:red">Error connecting to LinkedIn! try again later!</h3>';
    }
}elseif(isset($_GET["oauth_problem"]) && $_GET["oauth_problem"] <> ""){
    $output = '<h3 style="color:red">'.$_GET["oauth_problem"].'</h3>';
}else{
    $authUrl = '?oauth_init=1';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Login with LinkedIn using PHP by CodexWorld</title>
    <link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<!-- Display login button / profile information -->
<?php echo $output; ?>
<?php
if(!empty($authUrl)){
    echo '<div class="linkedin_btn"><a href="'.$authUrl.'"><img src="images/sign-in-with-linkedin.png" /></a></div>';
}
?>
</body>
</html>

Logout (logout.php)

When the user wishes to log out from their account, the user would be redirected to the logout.php file.

<?php
//start session
session_start();

//Unset token and user data from session
unset($_SESSION['oauth_status']);
unset($_SESSION['userData']);

//Destroy entire session
session_destroy();

//Redirect to homepage
header("Location:index.php");
exit;
?>

Conclusion

We’ve tried to make LinkedIn login integration process simple as much as possible. Using our script, you can easily add Login with LinkedIn feature to your website. If you have any query or suggestions about this tutorial, feel free to comment here.

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