December 2, 2015 12:21 pm

How to Login with Facebook API SDK v5 in PHP

Previously we wrote many article on Facebook login and now they are not working due to updates in Facebook API so I am writing on latest SDK v5 how to login with Facebook using PHP SDK v5 which is the latest version and I suggest you all to update your old Facebook login integration to the latest version.How to Login with Facebook API SDK v5 in PHP

[wpdm_file id=156]DEMO

Let’s Start

Make New Application on Facebook:

1. Visit https://developers.facebook.com/apps and click + Create New App.

create facebook application

Click on website.

create facebook application name

Add application name and click Create New Facebook App ID.

create facebook application select category

Select category and click on Create App ID. On next window click Skip Quick Start.

It will take you to the app dashboard now select settings and click on +Add Platform. Select website in add platform popup.

create facebook application select platform

Add your website link and fill form and save like below image.

create facebook application form saved

By default your app enabled for sandbox mode you need to change it to live click on Status & Review.

create facebook application make app live

That’s it App settings done now come to the coding.

First of all download SDK from here or you can download our demo code which contain SDK as well.

Now create a file index.php and add a facebook login button link to fblogin.php page and create a callback.php page to show information after authenticate.

index.php

<!DOCTYPE html>
<html>
<head>
<title>Login With Facebook</title>
</head>
<body>
  <a href="fblogin.php"><img src="login-button.png" alt="Facebook Login Button"></a>
</body>
</html>

It will show a login with Facebook image.

fblogin.php

<?php
session_start();
require_once( 'Facebook/autoload.php' );

$fb = new Facebook\Facebook([
  'app_id' => 'ENTER-YOUR-APP-ID',
  'app_secret' => 'ENTER-YOUR-APP-SECRET',
  'default_graph_version' => 'v2.5',
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email']; // Optional permissions for more permission you need to send your application for review
$loginUrl = $helper->getLoginUrl('http://demo.phpgang.com/facebook-login-sdk-v5/callback.php', $permissions);
header("location: ".$loginUrl);

?>

This page verify your Facebook application credentials and redirect you to facebook.com for login. You need to change your application id and application secret.

Once you allow all permission it will redirect to callback.php page and show your user’s data.

callback.php

<?php
session_start();
require_once( 'Facebook/autoload.php' );
require_once( 'db.php' );

$fb = new Facebook\Facebook([
  'app_id' => 'ENTER-YOUR-APP-ID',
  'app_secret' => 'ENTER-YOUR-APP-SECRET',
  'default_graph_version' => 'v2.5',
]);  
  
$helper = $fb->getRedirectLoginHelper();  
  
try {  
  $accessToken = $helper->getAccessToken();  
} catch(Facebook\Exceptions\FacebookResponseException $e) {  
  // When Graph returns an error  
  
  echo 'Graph returned an error: ' . $e->getMessage();  
  exit;  
} catch(Facebook\Exceptions\FacebookSDKException $e) {  
  // When validation fails or other local issues  

  echo 'Facebook SDK returned an error: ' . $e->getMessage();  
  exit;  
}  


try {
  // Get the Facebook\GraphNodes\GraphUser object for the current user.
  // If you provided a 'default_access_token', the '{access-token}' is optional.
  $response = $fb->get('/me?fields=id,name,email,first_name,last_name', $accessToken->getValue());
//  print_r($response);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'ERROR: Graph ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'ERROR: validation fails ' . $e->getMessage();
  exit;
}
$me = $response->getGraphUser();
//print_r($me);
echo "Full Name: ".$me->getProperty('name')."<br>";
echo "First Name: ".$me->getProperty('first_name')."<br>";
echo "Last Name: ".$me->getProperty('last_name')."<br>";
echo "Email: ".$me->getProperty('email');
echo "Facebook ID: <a href='https://www.facebook.com/".$me->getProperty('id')."' target='_blank'>".$me->getProperty('id')."</a>";
?>

That’s it for codding end now you can integrate it and run latest version of Facebook login.

Note: This version of the Facebook SDK for PHP requires PHP 5.5 or greater.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

91 responses to “How to Login with Facebook API SDK v5 in PHP”

  1. majeed says:

    hello my dear .. this not working ..error message.. Invalid App ID: {455718634633119}
    please help me

  2. Sanjay Kumar Singh says:

    It is giving….
    Facebook SDK returned an error: Connection timed out after 10001 milliseconds

  3. Dhanashri Bhirud-Fegde says:

    hello, its not working. error message Warning: Unexpected character in input: ” (ASCII=92) state=1 and Parse error: syntax error, unexpected T_STRING in
    plz help

  4. Gagandeep Sharma says:

    Hello, everytime i am getting error “Facebook SDK returned an error: Cross-site request forgery validation failed. Required param “state” missing.” but State is available in the get URL parameters while callback.

  5. Luca Olivieri says:

    good Work thanks…. i have a question? can i ask permission and get account phone number ? or phone number it’s only for page informations?

  6. Luca Olivieri says:

    good Work thanks…. i have a question? can i ask permission and get account phone number ? or phone number it’s only for page informations?

  7. Luca Olivieri says:

    good Work thanks…. i have a question? can i ask permission and get account phone number ? or phone number it’s only for page informations?

  8. Luca Olivieri says:

    good Work thanks…. i have a question? can i ask permission and get account phone number ? or phone number it’s only for page informations?

  9. Gagandeep Sharma says:

    @huzoorbux:disqus
    I am getting

    Call to a member function getValue() on a non-object on $response = $fb->get(‘/me?fields=id,name,email,first_name,last_name’, $accessToken->getValue());

  10. @huzoorbux:disqus
    Downloaded file not working. I haven’t replaced anything.

    Facebook SDK returned an error: couldn’t connect to host

  11. Toqeer Khan says:

    Great work i downloaded That its work perfect Thanks …….

  12. Manzoor Mustafa says:

    It is working perfectly. I can bet that there can’t be such beautiful tutorial any where else. Really it is awesome

  13. Manzoor Mustafa says:

    It is working perfectly. I can bet that there can’t be such beautiful tutorial any where else. Really it is awesome

  14. Manzoor Mustafa says:

    It is working perfectly. I can bet that there can’t be such beautiful tutorial any where else. Really it is awesome

  15. Manzoor Mustafa says:

    It is working perfectly. I can bet that there can’t be such beautiful tutorial any where else. Really it is awesome

  16. Gautam says:

    Parse error: syntax error, unexpected ‘[‘, expecting ‘)’ in D:wampwwwDemosfacebookLoginDemofblogin.php on line 4

  17. Vishal Kumar says:

    Facebook SDK returned an error: Connection timed out after 10001 milliseconds

  18. Soniya Kukreja says:

    nice tutorial

  19. Soniya Kukreja says:

    nice!

  20. Darío says:

    help please! Parse error: syntax error, unexpected ‘[‘, expecting ‘)’ in C:Amppswwwfbfblogin.php on line 5

    • Svetlana Antonova says:

      This error appears because your PHP version is lower than 5.4. Facebook config array is written with square brackets. If you can’t upgrade PHP version solution I used is to replace “[xxxxx => yyyy]” array definition with “array(xxxx=>yyyy)” in your files as well as Facebook PHP SDK files.
      Facebook SDK 5.0 requires min PHP 5.4

  21. Darío says:

    help please! Parse error: syntax error, unexpected ‘[‘, expecting ‘)’ in C:Amppswwwfbfblogin.php on line 5

  22. Darío says:

    help please! Parse error: syntax error, unexpected ‘[‘, expecting ‘)’ in C:Amppswwwfbfblogin.php on line 5

  23. Darío says:

    help please! Parse error: syntax error, unexpected ‘[‘, expecting ‘)’ in C:Amppswwwfbfblogin.php on line 5

  24. Darío says:

    help please! Parse error: syntax error, unexpected ‘[‘, expecting ‘)’ in C:Amppswwwfbfblogin.php on line 5

  25. Darío says:

    help please! Parse error: syntax error, unexpected ‘[‘, expecting ‘)’ in C:Amppswwwfbfblogin.php on line 5

  26. Renata says:

    Is it possible to capture my posts and hometown/location ?

    If I increment the code as:
    get(‘/me?fields=id,name,email,first_name,last_name,posts,location,hometown’)

    and :
    echo “Posts: “.$me->getProperty(‘posts’).””;

    Is it possible? Because I increment this and it did not work.

    Thanks!!

  27. saurabh says:

    Facebook SDK returned an error: Connection timed out after 10001 milliseconds

  28. saurabh says:

    link -http://haridwaryatra.com/fb/

    Getting Error – Facebook SDK returned an error: Connection timed out after 10001 milliseconds

  29. baljit says:

    Hello

    Hope you are doing great

    we are using facebook APi when i have click facebook login then redirect to my site its display error message “An Internal Error Has Occurred
    Error: An Internal Error Has Occurred.” and not $accessToken = $helper->getAccessToken(); print access token

    please let us know how can do it in cakephp 3.1

  30. Koushik Dutta says:

    Hello sir,
    This bunch of code is not working it will show a error -> ” Facebook SDK returned an error: Connection timed out after 10001 milliseconds

  31. Koushik Dutta says:

    And sir I am sure about my Php version is grater than 5.5..

  32. Koushik Dutta says:

    OK sir

  33. clipfever says:

    How to get Profile url (Ex. fb.com/your_profile_user_name)

  34. Naveen Yadav says:

    when I run this script code I got this error “Warning: Unexpected character in input: ” (ASCII=92) state=1…line no. 5″ there is “$fb = new FacebookFacebook([” where I mistake??
    also same line second error this
    “Parse error: syntax error, unexpected T_STRING” line no. 5

  35. Anil Singh says:

    Thanks for the great post.
    I am stuck as some issue here about how to pass the appsecret_proof param to the fb request. I have added a question with complete details here as well – http://stackoverflow.com/questions/40500252/passing-appsecret-proof-in-fb-request
    Can someone help me figure it out. Thanks.

  36. Mary Smith says:

    Thanks for the great post. Have you developed code to post message, image on FB page using V5 sdk? If yes please share

  37. Mary Smith says:

    Thanks for the great post. Have you developed code to post message, image on FB page using V5 sdk? If yes please share

  38. Mary Smith says:

    Thanks for the great post. Have you developed code to post message, image on FB page using V5 sdk? If yes please share

  39. Christopher Grigg says:

    Thanks that’s great, FB doco’s are not good!

  40. Koushik Dutta says:

    Hello Sir,
    I wanna make a image gallery by using Facebook uploaded pictures.Sir would u like to help me out? please

  41. Varun Nayyar says:

    Nice tutorial

  42. Anant Jain says:

    FB updated its API version, now its not working, please help

  43. Vijay Thakor says:

    Fb updated their API version and now my login with facebook functionality not working, please help me

  44. Ogudu Chima says:

    i go this:
    Facebook SDK returned an error: Connection timed out after 10001 milliseconds

  45. Max John says:

    Thank you very much. This is one the best tutorial ever on the subject

  46. Max John says:

    Can you please add how to log the member out ?

Leave a Reply

Your email address will not be published. Required fields are marked *