How to login with LinkedIn oAuth2 in PHP and MySQL
LinkedIn is a business oriented social networking platform and used for professional networking. We create a tutorial on login with LinkedIn oAuth which is not working properly and difficult to configure for developers, after receiving many complains from readers I am writing this new tutorial on LinkedIn oAuth2 it’s super easy to integrate with your website in few simple steps.
Let’s start.
Step 1: Goto https://www.linkedin.com/developer/apps/ and click Create Application button.
Step 2: Fill all information of your application.
Press Submit button it will redirect you to the application page.
Step 3: Add callback URL on application page.
Press Update and you are done with application settings.
Now Move the the database section
Create users table follow structure below:
-- -- Database: `linkedin` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userid` varchar(30) NOT NULL, `firstName` varchar(100) NOT NULL, `lastName` varchar(100) NOT NULL, `emailAddress` varchar(100) NOT NULL, `position` varchar(200) NOT NULL, `location` varchar(40) NOT NULL, `profileURL` varchar(200) NOT NULL, `pictureUrls` text NOT NULL, `headline` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
PHP Code
db.php
<?php define('DB_SERVER', 'localhost'); // Database server define('DB_USERNAME', 'username'); // Database Username define('DB_PASSWORD', 'password'); // Database Password define('DB_DATABASE', 'database'); // Database Name $connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE); // connecting with database ?>
Edit above file as per your database configuration.
config.php
<?php $config['callback_url'] = ''; //Your callback URL $config['Client_ID'] = ''; // Your LinkedIn Application Client ID $config['Client_Secret'] = ''; // Your LinkedIn Application Client Secret ?>
Edit config file and add you application information. check application page step 2.
index.php
Include config.php and db.php files in index file
<?php require_once('config.php'); require_once('db.php'); ?>
Below code will verify your configuration.
<?php if ($config['Client_ID'] === '' || $config['Client_Secret'] === '') { echo 'You need a API Key and Secret Key to test the sample code. Get one from <a href="https://www.linkedin.com/developer/apps/">https://www.linkedin.com/developer/apps/</a>'; exit; } ?>
Login button section
<?php echo '<a href="https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id='.$config['Client_ID'].'&redirect_uri='.$config['callback_url'].'&state=98765EeFWf45A53sdfKef4233&scope=r_basicprofile r_emailaddress"><img src="./images/linkedin_connect_button.png" alt="Sign in with LinkedIn"/></a>'; ?>
Callback code section on index.php file
<?php if(isset($_GET['code'])) // get code after authorization { $url = 'https://www.linkedin.com/uas/oauth2/accessToken'; $param = 'grant_type=authorization_code&code='.$_GET['code'].'&redirect_uri='.$config['callback_url'].'&client_id='.$config['Client_ID'].'&client_secret='.$config['Client_Secret']; $return = (json_decode(post_curl($url,$param),true)); // Request for access token if($return['error']) // if invalid output error { $content = 'Some error occured<br><br>'.$return['error_description'].'<br><br>Please Try again.'; } else // token received successfully { $url = 'https://api.linkedin.com/v1/people/~:(id,firstName,lastName,pictureUrls::(original),headline,publicProfileUrl,location,industry,positions,email-address)?format=json&oauth2_access_token='.$return['access_token']; $User = json_decode(post_curl($url)); // Request user information on received token // Insert Data in Database $query = "INSERT INTO `test`.`users` (`userid`, `firstName`, `lastName`, `emailAddress`, `position`, `location`, `profileURL`, `pictureUrls`, `headline`) VALUES ('$id', '$firstName', '$lastName', '$emailAddress', '$position', '$location', '$profileURL', '$pictureUrls', '$headline')"; mysqli_query($connection,$query); } } ?>
First off all we check if code received or not, using that code we will request for access_token once we get token we can get users information like name, email, picture and many more. In last step store that data in database.
That’s it all done and you have a output looks like this:
Tutorial Categories:
I recently worked on linkedin api. you can only get basic information through linkedin api. If you want to get full profile of the user through oauth, you have to submit your application to linkedin and tell them reasons why you need full profile access. If the approve your application, you can get full profile otherwise not.
Hello, nice example. Have you an advice, how to call linkedIn api using oAuth2 server-to-server (without login window)? We want to get count of likes and comments from our profile and save it to DB. I think, that standard oAuth2 implementation allows to set “grant_type” url parameter to value “client credentials” or “password” for testing and server to server communication. But LinkedIn supports only “authorization_code” and not others. Please, have you some idea, how to solve this?
You can store user’s access_token for future use token’s validity is 60 days after 60 days you can renew token.
I am trying to implement this in codeigniter framework. I m getting the blank details i guess the curl function is not returning the token.
Could you plz help me?
i Have already enabled the CURL
try to debug line by line. This code is super simple to implement.
Thank you ,it helps a lot.
Thank you for your support ,i have used it in my cakephp framework,its also working fine.
For me return this error:
Fatal error: Call to undefined function post_curl()
The line of code is: $return = (json_decode(post_curl($url,$param),true)); // Request for access token
please reply why locally it returns null
The method post_curl() is missing, if you download the script it will show at the bottom of the index-file, it is as follows:
function post_curl($url,$param=””)
{
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
if($param!=””)
curl_setopt($ch,CURLOPT_POSTFIELDS,$param);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
Thanks Done
Link not working to download code. Keep getting “Sorry no email found subscribe below.”
Im getting errors undefined variable id, firstname, lastname, etc..
Hi Huzoor Bux,
I am using linkedin API to get user data but not returning full profile data. is there any authorization required by linkedin?
$User has NULL value.. why??