Login System with LinkedIn using OAuth php and mysql

by  
Share:
Login System with LinkedIn using OAuth php and mysql

The “login system with social sites” series continues and this time its LinkedIn. LinkedIn is the largest professional network, and if you give user the facility to login via linkedin it will boost your login/register process. In this tutorial you will learn to create linkedin application for website and build Login System with LinkedIn using OAuth php and mysql.

View Demo

How login with LinkedIn works?

If you have read my post on Login System with Google using OAuth php and mysql it works exactly same as that.

  • You will have to create an application LinkedIn Developers site to get API KEY and SECRET KEY.
  • After you are done with Step 1 , you will go to the website say “http://demos.aarafacademy.com/login-system-with-linkedin/index.php” where you will click on login with linkedin button.
  • It will redirect you to linkedin_login.php which will redirect to Linkedin Site, where you will have to login with your linkedIn Credentials and then allow the permission to the application. It will redirect you back to your linkedin_login.php
  • If there is any error, it will send you back to index.php, or if everything is perfect it will check the database for existing email ID. If email ID does not exist it will save it with your name and email ID. and redirect to home.php. If email ID is already present in the database it will just redirect to home.php with welcome message.

Workflow of Login System with LinkedIn using OAuth php and mysql

 

How to create a LinkedIn Application

To get things started you will first have to get API KEY and SECRET KEY by making an application in LinkedIn Developers Site. Given below is the powerpoint presentation which will guide you through the process of making the a linkedIn Application.

 

Integration of LinkedIn with OAuth PHP and MySQL

Let’s start coding now. First of all create a database “login_system” and create a table “users.

CREATE DATABASE IF NOT EXISTS login_system;
USE login_system;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

Set all your credentials in config.php
// database related
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'login_system');

// try connecting with database
try {
  $DB = new PDO(DB_DRIVER . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $dboptions);
} catch (Exception $ex) {
  echo $ex->getMessage();
  die;
}

// LinkedIn and your website related credentials
define("API_KEY", "your api key");
define("SECRET_KEY", "your api secret");
// change with your site URL
define("SITE_URL", "http://demos.aarafacademy.com/login-system-with-linkedin/");
define("REDIRECT_URL", SITE_URL."linkedin_login.php");
// Set the scope 
define("SCOPE", 'r_basicprofile r_emailaddress' );
define("LOGOUT_URL", SITE_URL."logout.php");

Set your login and logout URL in index.php and home.php
<a href="linkedin_login.php">
  Login with LinkedIn
</a>

<a href="<?php echo LOGOUT_URL; ?>">
  Logout
</a>

Now the main part linkedin_login.php. Create an oauth object and try to connect with linkedin and get a response.
require('http.php');
require('oauth_client.php');
require('config.php');

$client = new oauth_client_class;
$client->debug = false;
$client->debug_http = true;
$client->redirect_uri = REDIRECT_URL;

$client->client_id = API_KEY;
$application_line = __LINE__;
$client->client_secret = SECRET_KEY;

if (strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
  die('Please go to LinkedIn Apps page');

$client->scope = SCOPE;
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,picture-url,public-profile-url,formatted-name)', 
					'GET', array(
						'format'=>'json'
					), array('FailOnAccessError'=>true), $user);
    }
  }
  $success = $client->Finalize($success);
}
if ($client->exit) exit;

You will get user data on successfull sign in. Save the email id and name if they dont exist in database.
if ($success) {
  // Now check if user exist with same email ID
  $sql = "SELECT COUNT(*) AS count from linkedin_users where email = :email_id";
  try {
    $stmt = $DB->prepare($sql);
    $stmt->bindValue(":email_id", $user->emailAddress);
    $stmt->execute();
    $result = $stmt->fetchAll();

    if ($result[0]["count"] > 0) {
      // User Exist 

      $_SESSION["name"] = $user->formattedName;
      $_SESSION["email"] = $user->emailAddress;
      $_SESSION["new_user"] = "no";
    } else {
      // New user, Insert in database
      $sql = "INSERT INTO `linkedin_users` (`name`, `email`) VALUES " . "( :name, :email)";
      $stmt = $DB->prepare($sql);
      $stmt->bindValue(":name", $user->formattedName);
      $stmt->bindValue(":email", $user->emailAddress);
      $stmt->execute();
      $result = $stmt->rowCount();
      if ($result > 0) {
        $_SESSION["name"] = $user->formattedName;
        $_SESSION["email"] = $user->emailAddress;
        $_SESSION["new_user"] = "yes";
        $_SESSION["e_msg"] = "";
      }
    }
  } catch (Exception $ex) {
    $_SESSION["e_msg"] = $ex->getMessage();
  }

  $_SESSION["user_id"] = $user->id;
} else {
  $_SESSION["e_msg"] = $client->error;
}

The final part is to display the results on the user screen i.e. on home.php
<?php if ($_SESSION["new_user"] == "yes") { ?>
<h2>Thank you <?php echo $_SESSION["name"] ?>, for registering with us!!!</h2>
<?php } else { ?>
<h2>Welcome back <?php echo $_SESSION["name"] ?>!!!</h2>
  <?php } ?>
<h5>Your email id is: <span style="text-decoration:underline;"><?php echo $_SESSION["email"]; ?></span></h5>

View Demo
Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Deena on

Hi,
This coding not work for me.when i click linkedin button it load same page not to redirect linkedin login page.Please help me

Reply
Shahrukh Khan on

is the code working on my website demo?

Reply
Ankit on

I am having same issue when i clicked on button it loade same page

Shahrukh Khan on

check your session?

adedeji on

How can I download http.php, oauth_client.php

Reply
Shahrukh Khan on

Click on the social link at the bottom to unlock the download link.

Reply
Tex on

The download link is not working. When I click on it i get a blank page.

Reply
Shahrukh Khan on

Please try again on the social link again it will work.

Reply
kp on

thanks, your code is working for me . how to fetch image i mean profile pic of linkedin User?

Reply
Ravi on

Hi code is working, but every time I have to enter email and password, how to save access_token so next time user won’t get dialog box?

Reply
Shahrukh Khan on

You can save the linkedIn ID in your database and then check whenever the user login.

Reply
Arpita Singh on

Hello…
I am unable to integrate LinkedIn in my project properly. It is giving following error:
it was not possible to open the OAuth request token URL: 110 could not connect to the host “api.linkedin.com”
I followed your code step by step.

Please Help…Thanks……..

Reply
Shahrukh Khan on

make sure the linkedin credentials are right

Reply
Waseem Abbas on

Can I check this on localhost? In case, I can what URL should I be providing in config.php where we are supposed to define site_url?

Reply
rohit on

How to show profile picture and company data ?

Reply
Max on

it was not possible to open the OAuth request token URL: 110 could not connect to the host “api.linkedin.com”….
How to solve…Please thanks

Reply
nisha on

this code work for me properly.thanks

Reply
Shahrukh Khan on

Your welcome.

Reply
kunal on

how can i intigrate google ,facebook and linkedinn social logins on a single application?

Shahrukh Khan on

You need to redirect user to specific site, let them allow permission and then give their details. when the code returns the data, you can use it for your system.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.