December 30, 2023 5:02 am

How to Login with Facebook Graph API in PHP

I have been working on facebook apps and connection with Facebook Graph API access tocken. This post will explain you how to integrate facebook connect in your website in easy way to connect and read the Facebook home timeline with PHP. Explained how to get facebook token and user id hope you like it. Thanks !

facebook graph 2

Updated SDK 100% Working!!

Make New Application on Facebook:

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

 

facebook graph 1

 

The script contains two folders called oAuth and images with PHP files.

src

– base_facebook.php // Class Get user Info

– facebook.php // Class Get user Info

– config.php // Configuration file

images

html.inc // html design view

index.php // Main index file show data

 PHP Code

Edit config.php

<?php

$config['callback_url']         =   'CALL BACK URL/?fbTrue=true'; //    /?fbTrue=true allow you to code process section.

//Facebook configuration
$config['App_ID']      =   'Your App ID';
$config['App_Secret']  =   'Your App Secret'; 

?>

 

Index.php

While clicking Login with Facebook button URL requesting Facebook Graph API with contains your web project redirection URL:

$config['callback_url'] = "http://www.yoursite.com/index.php/?fbTrue=true"; // added in config.php

.

login-button

<a href="https://www.facebook.com/dialog/oauth?client_id='.$config['App_ID'].'&redirect_uri='.$config['callback_url'].'&scope=email,user_likes,publish_stream"><img src="./images/login-button.png" alt="Sign in with Facebook"/></a>

 

<?php
require 'src/config.php';
require 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => $config['App_ID'],
  'secret' => $config['App_Secret'],
  'cookie' => true
));

if(isset($_GET['fbTrue']))
{
    $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=".$config['App_ID']."&redirect_uri=" . urlencode($config['callback_url'])
       . "&client_secret=".$config['App_Secret']."&code=" . $_GET['code']; 

     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);

     $graph_url = "https://graph.facebook.com/me?access_token=" 
       . $params['access_token'];

     $user = json_decode(file_get_contents($graph_url));
     $content = $user;
}
else
{
    $content = '<a href="https://www.facebook.com/dialog/oauth?client_id='.$config['App_ID'].'&redirect_uri='.$config['callback_url'].'&scope=email,user_likes,publish_stream"><img src="./images/login-button.png" alt="Sign in with Facebook"/></a>';
}

include('html.inc');

Next Tutorial on Google Login.

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:

102 responses to “How to Login with Facebook Graph API in PHP”

  1. Shafiqul says:

    Very nice topic. It is very useful for Facebook Group API in PHP programming.

    • Huzoor Bux says:

      Some thing is wrong in your code application working fine and returning with code.

      • ramakanth says:

        FROM WHICH PAGE WE CAN GET THE USER DEATAILS IN FACEBOOK API??
        AND HOW TO POST THE USER DEATILS INTO DATABASE OR PARTICULAR PAGE???

        • Huzoor Bux says:

          Check code in index.php for data.

          if(isset($_GET[‘fbTrue’]))
          {
          $token_url = “https://graph.facebook.com/oauth/access_token?”
          . “client_id=”.$config[‘App_ID’].”&redirect_uri=” . urlencode($config[‘callback_url’])
          . “&client_secret=”.$config[‘App_Secret’].”&code=” . $_GET[‘code’];

          $response = file_get_contents($token_url);
          $params = null;
          parse_str($response, $params);

          $graph_url = “https://graph.facebook.com/me?access_token=”
          . $params[‘access_token’];

          $user = json_decode(file_get_contents($graph_url));
          $content = $user;
          }

          • I’m not worthy, I’M NOT WORTHY! Oh, great and powerful Facebook wizard, you are the first person — THE FIRST PERSON — who has actually published a functional example of a Facebook authentication chain!

            I’ve been struggling with this and other problems with the Facebook API for an *ENTIRE YEAR* — an entire year!

            I start on trying to solve the problem, and then I stop for a while, out of frustration.

            Can you please recommend the reference materials (books? e-books?) that you used to figure this out???? Also, please consider writing and publishing your own book on the subject. I’ll be the first to buy it!

            Thank you, so much!

      • I am not getting user details however login with facebook working properly what whould be the problem….

        • Huzoor Bux says:

          Use exact given demo code might be you are making some mistake or edit something in it please recheck your code or paste it here.

  2. Many thanks, again to Huzoor Bux. I’ve made a few changes to the procedure described, herein, and outline them in a blog entry of my own: http://wexblog.prwexler.com/2013/04/11/a-simple-facebook-authentication-chain.aspx

  3. hyipbox says:

    Hello, I cannot download this. It keeps saying im not subscribed although i already am. Please help

  4. anurup says:

    Hi. i use your code but the content is not showing. please help me.

  5. anu says:

    hello sir , this code is not working.its returning..http://ohchoky.com/booking2/travel/index.php?code=…….

  6. Nikhil Hole says:

    Can you provide code for logout from site..?

    • huzoorbux says:

      Script is updated and below is the for log out from fb. You can also download complete code or you can check in our demo for testing.

      $url = ‘https://www.facebook.com/logout.php?next=’ . urlencode(‘http://demo.phpgang.com/facebook_login_graph_api/’) .
      ‘&access_token=’.$_GET[‘tocken’];
      session_destroy();
      header(‘Location: ‘.$url);

  7. Eldy Voon says:

    it appear to have long URL after the user have logged in..

  8. Luca Pandolfo says:

    I have a problem when I refresh the page. I lost the data of fb login. Can you help me?

  9. larry says:

    hello and thanks for the tutorial… its the best I’ve seen so far (been struggling for several days now)… anyway

    I have it working, but added this part:
    // your code
    test_login($config, $facebook) ? validLogin() : userLoginScreen($config);
    print “You are logged in!n”;

    // the above works, but
    //this below causes this error:
    //Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.

    $user_profile = $facebook->api(‘/me’,’GET’);
    echo “email: ” . $user_profile[’email’];

    ====
    so where or how do I get the user email’s address?

    thanks!

  10. Luca Pandolfo says:

    When I log in, can hide fbTrue and code from the domain address?

  11. Subhash Kapil says:

    hi sir, i’m getting the following in this script:

    Secure Connection Failed

    An error occurred during a connection to taurustrip com.
    SSL received a record that exceeded the maximum permissible length.
    (Error code: ssl_error_rx_record_too_long)

    The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.Please contact the website owners to inform them of this problem. Alternatively, use the command found in the help menu to report this broken site.

  12. Subhash Kapil says:

    hi sir, this is the callback url you asked. Did i do something wrong in it? please help.

    $config[‘callback_url’] = ‘https://taurustrip com/projectjob/facebook_login_graph_api/index.php/?fbTrue=true’;

    • huzoorbux says:

      Your website is not ssl supported please use http:// instead of https:// it will work properly.

      • Subhash Kapil says:

        I now using http instead of https & script is running now but it is showing me a blank page with coming soon text on the page.

        you may see it here:

        www{.}taurustrip{.}com/projectjob/facebook_login_graph_api

  13. Subhash Kapil says:

    i now using http instead of https as you told me & script is running now but it is showing me a blank page with text: Coming soon.. instead of logout button.

    you may see it here
    www{.}taurustrip{.}com/projectjob/facebook_login_graph_api

  14. Sagar Patil says:

    Hi
    i have face following error Please help

    Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App’s settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App’s domains.

  15. Sunnie says:

    Hello, I cannot download this. It keeps saying i’m not subscribed. Please help

  16. huzoorbux says:

    Use exact url instead of only page name.

  17. Sharaniya says:

    is it possible to do the above procedure by just running the web application in localhost ??

  18. tigere rangwani says:

    How about registering user on local db, using info provided from facebook?

  19. hello every one can we open it in pop up with responsive facebook

  20. Srikanth says:

    This source was working but the issue was after authentication on facebook it was redirecting to the call back url and displaying nothing can you please help me out

  21. Vaibhav says:

    logout button not visible… can you help me??

  22. Rahul Sati says:

    everything is done but i’m still at the end . i don’t get any output..is anything a missed apart from this.

  23. ron says:

    I can’t download your script, even though I subscribed. 🙁

  24. Xuan Vichia says:

    Warning: file_get_contents(https://graph.facebook.com/me?access_token=) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in facebook_login_graph_api/index.php on line 33
    pls help me

  25. Navneet Soni says:

    how to get friend list by this api help me..

  26. bhathu says:

    suscribed but not downloaded why..

  27. Akilan says:

    hi….i cant get logout link

  28. abhijit says:

    hi huzoor bux…thanks for such article…can you please help me how to get only the friends name and email address using this code

  29. Hi sir … thanks for share this article, this is really helpful for me. Good job.

  30. usman says:

    sir i have authorization problem in this code

  31. usman says:

    this is showing content in array form

  32. Rezky Balweel says:

    i got a problem:

    Warning: file_get_contents(https://graph.facebook.com/me?access_token=): failed to open stream: Connection refused in /home/u504800903/public_html/facebook_login_graph_api/index.php on line 34

  33. It'z UR Friend says:

    it logins but then it only displays username & fb id , i wants to display email & logout button too. plz help me bhaijaan.

    • Anirudh Mangalvedhekar says:

      This is kind of old my friend. Graph API has been updated. To get the email Id you will need to put it in scope parameter..

  34. Nitin Sebastien says:

    how to fix the error Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App’s settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App’s domains.

  35. Nitin Sebastien says:

    how to get mobile number or email id of people who logged through Facebook into our website

  36. Nitin Sebastien says:

    how to get the user info such as mobile number ,email,name people who logged through Facebook into our website ,please help me itz urgent

  37. kishan says:

    hi huzoor bux…thanks for such article…can you please help me how to get only the friends name and email address using this code

  38. kishan says:

    .can you please help me how to get only the friends name and email address using this code in facebook login in php

  39. Nitin Sebastien says:

    same error .any soultion for this error?

  40. Yunus says:

    i can only see the id and the name. Why can i not see the location and gender?

  41. Create a rewrite rule.. for php it is mod_rewrite and for IIS it is URL_rewrite plugin. Make a write rule that all formats with www at the start be turn into non www version. Consult your local server’s manuals on how to do it. Register the one without www

  42. Hahahaah have you try by decline permission. You will see error with logout button. Write better script or stop writing.

    • Westland Resident says:

      If you have nothing constructive to say don’t say anything. This guy has written a good script and certainly gets you thinking. All programmers make mistakes if they didn’t we wouldn’t never see such emphasis on debugging.

    • Westland Resident says:

      If you have nothing constructive to say don’t say anything. This guy has written a good script and certainly gets you thinking. All programmers make mistakes if they didn’t we wouldn’t never see such emphasis on debugging.

    • Westland Resident says:

      If you have nothing constructive to say don’t say anything. This guy has written a good script and certainly gets you thinking. All programmers make mistakes if they didn’t we wouldn’t never see such emphasis on debugging.

    • Westland Resident says:

      If you have nothing constructive to say don’t say anything. This guy has written a good script and certainly gets you thinking. All programmers make mistakes if they didn’t we wouldn’t never see such emphasis on debugging.

  43. odzk says:

    Hello, Im getting an error

    “Invalid redirect_uri: Given URL is not allowed by the Application configuration”, Im thinking that this method is already outdated. they facebook updated the graph api? Thanks

Leave a Reply

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