December 16, 2012 7:14 pm

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

 

Index.php

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

.

login-button

 

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:
  • Very nice topic. It is very useful for Facebook Group API in PHP programming.

  • not working
    here’s my app http://demo.phpgang.com

    • Huzoor Bux

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

      • ramakanth

        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

          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

          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.

  • 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

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

    • huzoorbux

      @hyipboxcom:disqus you are in list now please download code.

      • Pratyush

        It keeps saying im not subscribed although i already am. Please help

  • anurup

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

  • anu

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

  • Nikhil Hole

    Can you provide code for logout from site..?

    • huzoorbux

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

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

  • Luca Pandolfo

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

    • huzoorbux

      you have to save that data to show after reload.

  • larry

    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!

  • Luca Pandolfo

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

    • huzoorbux

      Yes you can store data on session or cookie and redirect without url query strings.

  • Subhash Kapil

    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.

    • huzoorbux

      Share your callback url.

  • Subhash Kapil

    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

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

      • Subhash Kapil

        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

  • Subhash Kapil

    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

  • Sagar Patil

    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.

    • Manisha Gaidhane

      same thing happen with me, i have tried to create facebook app with localhost url and registred domain it is “Something went wrong. We’re working on getting it fixed as soon as we can”

      • huzoorbux

        You must have a hosted application it will not work properly on localhost.

        • Manisha Gaidhane

          Thanks for your reply, but it is giving me same error for hosted application also

      • Sagar

        thank you i will also work on it and fixed it as soon as

    • huzoorbux

      You have to add domain on which you are receiving request like in this image.

      • Sagar

        thank you

        i will try it on live

  • Sunnie

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

  • huzoorbux

    Use exact url instead of only page name.

    • Manisha Gaidhane

      i tried with that but its not working

  • Sharaniya

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

    • huzoorbux

      Not possible on localhost use some host to do that.

      • tigere rangwani

        Actually you can run this on local host if you place your localhost/folder url in your app settings/Advanced
        Valid OAuth redirect URIs –

  • tigere rangwani

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

  • App

    Shit

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

  • Srikanth

    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

    • Maneesh

      config.php call back url change karo

  • Vaibhav

    logout button not visible… can you help me??

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

    • huzoorbux

      turn on errors and try again you might get some error on that page.

      • hi, Thank you so much.. i will try this

  • ron

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

  • Xuan Vichia

    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

  • Navneet Soni

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

  • bhathu

    suscribed but not downloaded why..

  • Akilan

    hi….i cant get logout link

  • abhijit

    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

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

  • usman

    sir i have authorization problem in this code

  • usman

    this is showing content in array form

  • Rezky Balweel

    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

    • Super Seo

      I’ve got the same issue, did you find any solution for this Rezky? Thank you

    • Super Seo

      I’ve got the same issue, did you find any solution for this Rezky? Thank you

  • It’z UR Friend

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

    • Anirudh Mangalvedhekar

      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..

  • Nitin Sebastien

    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.

  • Nitin Sebastien

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

  • Nitin Sebastien

    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

    • You can get email by requesting email in scope like this scope=email. Facebook not allowed to get mobile number in api.

      • Nitin Sebastien

        i can’t get the email id using this scope=email ,getting only appid and name

        • Please share link.

          • Nitin Sebastien

            $content = ‘‘;

          • Nitin Sebastien

            please help me

          • your website Link please?

          • Nitin Sebastien

            https://www.facebook.com/dialog/oauth?client_id=‘.$config[‘App_ID’].’&redirect_uri=’.$config[‘callback_url’].’&scope=email

          • Nitin Sebastien

            this is the link $content = ‘‘;

          • Nitin Sebastien

            $content = ‘‘;

    • You can get email by requesting email in scope like this scope=email. Facebook not allowed to get mobile number in api.

  • kishan

    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

  • kishan

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

  • Nitin Sebastien

    same error .any soultion for this error?

  • Yunus

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

  • 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

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

    • Westland Resident

      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

      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

      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

      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.

  • odzk

    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

    • What URL you are sending?

      • odzk

        I was able to get it working. but I can only get the name and ID no other information like email etc. I believe we need to change the /me? but I’m not sure what to change. Thanks