0 Sales


With an enormous user base, LinkedIn is one of the most popular social networks. Like the authentication of Facebook, Twitter and Google, LinkedIn was also used in the web application for user authentication. If you want the user to be able to login to the website's social account, the LinkedIn login option can add value to the social login system. Sign In with the LinkedIn function allows the user to use their LinkedIn profile to sign into the web application without creating a new account.


LinkedIn API helps in the web application to authenticate and access account information of the user. With the PHP OAuth library, you can easily integrate LinkedIn Authentication. OAuth library helps you to connect to the LinkedIn API and use PHP to connect to the LinkedIn profile. In this tutorial, we will show you how to integrate user registration and login framework using PHP with LinkedIn and store the data of the LinkedIn account in the MySQL server. Our LinkedIn login script example uses PHP OAuth 2.0 and LinkedIn login API v2 to construct PHP and MySQL LinkedIn login framework.


Before you start integrating Sign In with PHP using LinkedIn, look at the structure of the files.


├── config.php

├── index.php

├── logout.php

├── User.class.php

├── linkedin-oauth-client-php/

├── images/

│   ├── linkedin-sign-in-btn.png

└── css/

    └── style.css


Create LinkedIn App


You need to create an app in the LinkedIn Developer panel to access the LinkedIn API. At the time of accessing the LinkedIn API, Client ID and Client Secret must be defined. Follow the step-by-step guide to create a new LinkedIn App and generate Client ID and Client Secret in the LinkedIn Developers section.


  1. Visit the LinkedIn Developers page and login to the credentials of your LinkedIn account.

  2. To create a new LinkedIn app, press the Create app button.

  3. Provide your user details and press Create request to submit your application registration form.


  • Name of the user–Title of the software.

  • Business–The company's name.

  • Overview of the software–Application workflow.

  • App logo–Logo for the OAuth dialog to display.

  • Confidentiality policy URL–Privacy policy page URL.

  • Corporate email-Your email address.

  • Apps–Choose the apps you want to add to your phone.


  1. The page will be redirected to the App settings screen when the app is successfully created.

  2. Switch to the Auth tab » Scroll down to the Settings page of OAuth 2.0.


  • Specify the redirect URL in the fields of the redirect URLs and change the settings of the application.


  1. You will see the Client ID and Client Secret of your LinkedIn App in the User credentials tab. At the time of the call to the LinkedIn API, the App ID and App secret must be specified in the script.

Create Database Table


A table must be created in the database to store the user's profile information from LinkedIn. The following SQL creates a user table for holding the LinkedIn account information with some basic fields in the MySQL database.


CREATE TABLE `users` (


 `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,


) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


LinkedIn OAuth Library for PHP

The directory linkedin-oauth-client-php/ contains the library for LinkedIn API v2 of the OAuth 2.0 PHP client. You don't have to download it separately, all LinkedIn PHP OAuth required files are included in our PHP source code for LinkedIn Login.

User Class (User.class.php)

The user class uses PHP and MySQL to handle the operations related to the database (connect, insert, and update). It helps connect in the users table to the database and insert / update LinkedIn account data.


  • construct() –Links to the MySQL database.

  • CheckUser() –Insert or update the OAuth Provider and ID-based user profile data. Gives the account data of the user as an array.



 * User Class

 * This class is used for database related (connect, insert, and update) operations

 * @author

 * @url

 * @license


class User {

    private $dbHost     = DB_HOST;

    private $dbUsername = DB_USERNAME;

    private $dbPassword = DB_PASSWORD;

    private $dbName     = DB_NAME;

    private $userTbl    = DB_USER_TBL;


    function __construct(){


            // Connect to the database

            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);


                die("Failed to connect with MySQL: " . $conn->connect_error);


                $this->db = $conn;





    function checkUser($userData = array()){


            // 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 = NOW() WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";

                $update = $this->db->query($query);


                // 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 = NOW(), modified = NOW()";

                $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;




Site Settings and API Configuration (config.php)

The settings for the database and constant variables for the configuration of the LinkedIn API are defined in the config.php file.


Constants of the database: 


  • DB HOST–Specify the host of the database.

  • DB USERNAME–Enter the username of the database.

  • DB PASSWORD–Specify the password for the database.

  • DB NAME–Enter the name of the database.

  • DB USER TBL–Specify the name of the table that will store the account data of the user.


LinkedIn API Constants: 


  • LIN CLIENT ID–Specify App ID for LinkedIn. 

  • LIN CLIENT SECRET–Specify App Secret for LinkedIn.

  • LIN REDIRECT URL–The OAuth Callback URL is specified.


Call LinkedIn API: 

The PHP OAuth library is used to connect to and work with the OAuth client with the LinkedIn API.




 * Basic Site Settings and API Configuration


// Database configuration

define('DB_HOST', 'MySQL_Database_Host');

define('DB_USERNAME', 'MySQL_Database_Username');

define('DB_PASSWORD', 'MySQL_Database_Password');

define('DB_NAME', 'MySQL_Database_Name');

define('DB_USER_TBL', 'users');

// LinkedIn API configuration

define('LIN_CLIENT_ID', 'Insert_LinkedIn_App_ID');

define('LIN_CLIENT_SECRET', 'Insert_LinkedIn_App_Secret');

define('LIN_REDIRECT_URL', 'OAuth_Callback_URL');

define('LIN_SCOPE', 'r_liteprofile r_emailaddress'); //API permissions

// Start session




// Include the oauth client library

require_once 'linkedin-oauth-client-php/http.php';

require_once 'linkedin-oauth-client-php/oauth_client.php';


Login & Get LinkedIn Account Data (index.php)

The authentication process for the LinkedIn API is handled using PHP in this file.


  1. The authentication URL is initially created and the web page displays the LinkedIn Sign-in key.


  1. If your LinkedIn account is authenticated by the user, the following will happen:



  • Use LinkedIn Profile API v2 (https:/ and PHP, the profile data is obtained from the LinkedIn account.

  • To get the email address of the member (https:/ call the LinkedIn API.

  • Using the user class checkUser) (function, insert account data into the server.

  • The account information of the user is stored in the SESSION.

  • The website shows the specifics of the LinkedIn profile (OAuth ID, First Name, Last Name, Address, Photo, Connection, etc.).



// Include configuration file

require_once 'config.php';

// Include User class

require_once 'User.class.php';

$authUrl = $output = '';

// If user already verified 

if(isset($_SESSION['oauth_status']) && $_SESSION['oauth_status'] == 'verified' && !empty($_SESSION['userData'])){

    // Retrieve user's profile data from session

    $userData = $_SESSION['userData'];


    // Prepare output to show LinkedIn profile data


        $output  = '<h2>LinkedIn Profile Details</h2>';

        $output .= '<div class="ac-data">';

        $output .= '<img src="'.$userData['picture'].'"/>';

        $output .= '<p><b>LinkedIn ID:</b> '.$userData['oauth_uid'].'</p>';

        $output .= '<p><b>Name:</b> '.$userData['first_name'].' '.$userData['last_name'].'</p>';

        $output .= '<p><b>Email:</b> '.$userData['email'].'</p>';

        $output .= '<p><b>Logged in with:</b> LinkedIn'.'</p>';

        $output .= '<p><b>Profile Link:</b> <a href="'.$userData['link'].'" target="_blank">Click to visit LinkedIn page</a></p>';

        $output .= '<p><b>Logout from</b> <a href="logout.php">LinkedIn</a></p>';

        $output .= '</div>';


}elseif((isset($_GET["oauth_init"]) && $_GET["oauth_init"] == 1) || (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) || (isset($_GET['code']) && isset($_GET['state']))){

    $client = new oauth_client_class;


    $client->client_id = LIN_CLIENT_ID;

    $client->client_secret = LIN_CLIENT_SECRET;

    $client->redirect_uri = LIN_REDIRECT_URL;

    $client->scope = LIN_SCOPE;

    $client->debug = 1;

    $client->debug_http = 1;

    $application_line = __LINE__;


    if(strlen($client->client_id) == 0 || strlen($client->client_secret) == 0){

        die('Please go to LinkedIn Apps page , '.

            '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())){


                $client->error = $client->authorization_error;

                $success = false;


                $success = $client->CallAPI(


                    'GET', array(


                    ), array('FailOnAccessError'=>true), $userInfo);

                $emailRes = $client->CallAPI(


                    'GET', array(


                    ), array('FailOnAccessError'=>true), $userEmail);



        $success = $client->Finalize($success);



    if($client->exit) exit;



        $client->error = $client->authorization_error;

        $success = false;




        // Initialize User class

        $user = new User();


        // Getting user's profile data

        $inUserData = array();

        $inUserData['oauth_uid']  = !empty($userInfo->id)?$userInfo->id:'';

        $inUserData['first_name'] = !empty($userInfo->firstName->localized->en_US)?$userInfo->firstName->localized->en_US:'';

        $inUserData['last_name']  = !empty($userInfo->lastName->localized->en_US)?$userInfo->lastName->localized->en_US:'';

        $inUserData['email']      = !empty($userEmail->elements[0]->{'handle~'}->emailAddress)?$userEmail->elements[0]->{'handle~'}->emailAddress:'';

        $inUserData['picture']    = !empty($userInfo->profilePicture->{'displayImage~'}->elements[0]->identifiers[0]->identifier)?$userInfo->profilePicture->{'displayImage~'}->elements[0]->identifiers[0]->identifier:'';

        $inUserData['link']       = '';

        // Insert or update user data to the database

        $inUserData['oauth_provider'] = 'linkedin';

        $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: ./');


         $output = '<h3 style="color:red">Error connecting to LinkedIn! try again later!</h3><p>'.HtmlSpecialChars($client->error).'</p>';


}elseif(isset($_GET["oauth_problem"]) && $_GET["oauth_problem"] <> ""){

    $output = '<h3 style="color:red">'.$_GET["oauth_problem"].'</h3>';


    $authUrl = '?oauth_init=1';


    // Render LinkedIn login button

    $output = '<a href="?oauth_init=1"><img src="images/linkedin-sign-in-btn.png"></a>';



<!DOCTYPE html>

<html lang="en">


    <title>Login with LinkedIn using PHP by CodexWorld</title>


    <!-- Include stylesheet file -->

    <link rel="stylesheet" href="css/style.css"/>



<div class="container">

    <div class="in-box">

        <!-- Display login button / profile information -->

        <?php echo $output; ?>





Logout (logout.php)

The logout.php file will be loaded if the user wants to log out of their LinkedIn account.


  • Remove from the SESSION OAuth status and user data.

  • Turn the user back to the homepage.



// Start session




// Unset token and user data from session



// Destroy entire session


// Redirect to homepage






You can use it for personal or commercial projects. You can't resell it partially or in this form.


Create Date : May 14, 2020

Updated Date : May 14, 2020


Comments : 0

Downloads : 0