Facebook Login with PHP Graph SDK



Today we learn how to log a user in through Facebook using their PHP Graph SDK. We create a login link to Facebook, send them their with a pop up, they accept and get redirected back to our website. Upon redirect, we get an access token from Facebook which allows us to get the users information.

Step 1: Create a Facebook App and config.php

First thing, before do any coding, is to setup a Facebook App. The Facebook App will give us our App ID and App Secret which we will use in our code to connect to the API through the PHP Graph SDK.

The user flow happens like this. The user visits our website. If they are not logged in with Facebook, they are redirected to Facebook and prompted to accept our apps permissions. If they accept, they are redirected back to our website, we are given code, and use that code to generate and access token for that user. We then use that access token to call Facebook and ask for the users information.

  • Go to https://developers.facebook.com/apps/
  • Create a new App
  • Visit the App Dashboard to get your App ID and App Secret.
  • Create a config.php and add your App ID and App Secret to the code below.
<?php
    // your app id goes here
    define( 'MY_FB_APP_ID', 'YOUR-FB-APP-ID' );

    // place our app secret here
    define( 'MY_FB_APP_SECRET', 'YOUR-FB-APP-SECRET' );

Step 2: Create index.php

In this file we determine if the user is logged in with Facebook, has been redirected to our site from Facebook, or is not logged in at all. If there is an access token in the session, we can log the user in and grab their user information. If the user is not logged in but is being redirected from our Facebook App, there is a code $_GET variable we can use to get the user an access token, log them in, and get their user information. If all else fails, we display a “Log in with Facebook” link to the user.

<?php
    // require our config file and load the php graph sdk
    require 'config.php';
    require_once 'vendor/graph-sdk/autoload.php';

    // start the session
    session_start();

    $appCreds = array( // array to hold app creds from fb app
	    'app_id' => MY_FB_APP_ID,
	    'app_secret' => MY_FB_APP_SECRET,
	    'default_graph_version' => 'v3.2'
    );

    if ( isset( $_SESSION['fb_access_token'] ) && $_SESSION['fb_access_token'] ) { // if we have access token, add it to the app creds
	    $appCreds['default_access_token'] = $_SESSION['fb_access_token'];
    }

    if ( isset( $_SESSION['fb_access_token'] ) && $_SESSION['fb_access_token'] ) { // we have an access token, use it to get user info from fb
	    $isLoggedIn = true;
    } elseif ( isset( $_GET['code'] ) && !$_SESSION['fb_access_token'] ) { // user is coming from allowing our app
	    // create new facebook object and helper for getting access token
	    $fb = new \Facebook\Facebook( $appCreds );
	    $helper = $fb->getRedirectLoginHelper();

	    try { // get access token, save to session, and add to app creds
	        $accessToken = $helper->getAccessToken();
	        $_SESSION['fb_access_token'] = (string) $accessToken;
	        $appCreds['default_access_token'] = $_SESSION['fb_access_token'];
	        $isLoggedIn = true;
	    } 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;
	    }
    } else { // user is no logged in, display the login with facebook link
	    // create new facebook object and helper for getting access token
	    $fb = new \Facebook\Facebook( $appCreds );
	    $helper = $fb->getRedirectLoginHelper();

	    // user is not logged in
	    $isLoggedIn = false;
    }

    if ( $isLoggedIn ) { // logged in
	    // create new facebook object
	    $fb = new \Facebook\Facebook( $appCreds );

	    // call facebook and ask for name and picture
	    $facebookResponse = $fb->get( '/me?fields=first_name,last_name,picture' );
	    $facebookUser = $facebookResponse->getGraphUser();

	    // Use handler to get access token info
	    $oAuth2Client = $fb->getOAuth2Client();
	    $accessToken = $oAuth2Client->debugToken( $_SESSION['fb_access_token'] );

	    // display everything in the browser
	    ?>
	    <div><b>Logged in as <?php echo $facebookUser['first_name']; ?> <?php echo $facebookUser['last_name']; ?></b></div>
	    <div><b>FB User ID: <?php echo $facebookUser['id']; ?></b></div>
	    <div><img src="<?php echo $facebookUser['picture']['url']; ?>" /></div>
	    <br />
	    <br />
	    <hr />
	    <br />
	    <br />
	    <b>User Info</b>
	    <textarea style="height:200px;width:100%"><?php echo print_r( $facebookUser, true ); ?></textarea>
	    <br />
	    <br />
	    <b>Access Token</b>
	    <textarea style="height:200px;width:100%"><?php echo print_r( $accessToken, true ); ?></textarea>
	    <br />
	    <br />
	    <b>Access Token Expires</b>
	    <textarea style="height:100px;width:100%"><?php echo print_r( $accessToken->getExpiresAt(), true ); ?></textarea>
	    <br />
	    <br />
	    <b>Access Token Is Valid</b>
	    <textarea style="height:50px;width:100%"><?php echo print_r( $accessToken->getIsValid(), true ); ?></textarea>
	    <br />
	    <br />
	    <?php
    } else { // not logged in
	    $permissions = ['email']; // Optional permissions
	    $loginUrl = $helper->getLoginUrl( 'https://www.justinstolpe.com/blog_code/facebook_login_php/index.php', $permissions );

	    ?>
	    <a href="<?php echo $loginUrl; ?>">Log in with Facebook</a>
	    <?php
    }
?>

 

In our index.php  file we determine if the user is logged in with Facebook by checking for a valid access token. We save the access token to our session so we can get the users information if they come back to our site. We do this because calling the actual Facebook get access token function over and over again fast enough will produce an error. The access token also lives on for a while anyways so once the user has accepted our app, there is no need for a new access token until the old one has expired.

Links

Live Demo

YouTube Video

Code on GitHub

That is going to do it for this post! Leave any comments/questions/concerns below and thanks for stopping by the blog!

331 comments

  1. In today’s fast-paced world, staying informed about the latest advancements both locally and globally is more crucial than ever. With a plethora of news outlets struggling for attention, it’s important to find a trusted source that provides not just news, but insights, and stories that matter to you. This is where [url=https://www.usatoday.com/]USAtoday.com [/url], a leading online news agency in the USA, stands out. Our dedication to delivering the most current news about the USA and the world makes us a go-to resource for readers who seek to stay ahead of the curve.

    Subscribe for Exclusive Content: By subscribing to USAtoday.com, you gain access to exclusive content, newsletters, and updates that keep you ahead of the news cycle.

    [url=https://www.usatoday.com/]USAtoday.com [/url] is not just a news website; it’s a dynamic platform that empowers its readers through timely, accurate, and comprehensive reporting. As we navigate through an ever-changing landscape, our mission remains unwavering: to keep you informed, engaged, and connected. Subscribe to us today and become part of a community that values quality journalism and informed citizenship.

  2. Yoou really mae it sewm soo easxy wit your presentation bbut I inn finding
    this matgter too bbe really onne thing wbich I feel I would by noo means understand.
    It sort oof feels too comploex and ver broad for me.
    I’m having a ook aead ffor yolur subsequent submit, I’ll
    attemplt too gett thee cking oof it!

  3. Hey Ikbow tuis is off topic bbut I waas wondering if youu knew of any widgets
    I could add to my blog that automatifally tweet mmy newesxt twifter updates.
    I’ve een looking ffor a plug-in like his forr quite soe
    time and wwas hoping maybe you woulkd have some
    experience with sojething lke this. Please let mme
    know if you ruun into anything. I truly emjoy readxing yoour bog and I ook forward to your neww
    updates.

  4. Once your blog is more established, this list will be used to bring in money, and you will be thankful that you already took care of this.

  5. I will immediately grasp your rss feed as I can’t to find your email subscription link or e-newsletter service.Do you have any? Please permit me realize in order that I may subscribe.Thanks.

  6. A motivating discussion is definitely worth comment. I think that you ought to write more about this subject, it may not be a taboo subject but typically folks don’t talk about such issues. To the next! Kind regards!!

  7. YouTube is an marvellous tool incorporated with this to help the visibility of one’s business. So for being to have more views on youtube you must go and be proactive.

  8. Does anyone know whether I am able to purchase Just Delta 8 Cartridges (justdeltastore.com) at Infinite Vapor Coon Rapids, 79 85th Ave NW, Coon Rapids, MN, 55433?

  9. Thanks for the good writeup. It if truth be told was a entertainment account it. Look complex to far added agreeable from you! By the way, how could we communicate?

  10. Heya i’m for the primary time here. I found this board and I find It truly helpful & it helped me out much. I’m hoping to provide one thing back and help others such as you helped me.

  11. Aw, this was an extremely nice post. Spending some time and actual effort to make a superb article… but what can I say… I hesitate a lot and don’t seem to get nearly anything done.

  12. I do not even know how I ended up here, but I thought this postwas great. I do not know who you are but certainly you are goingto a famous blogger if you aren’t already 😉 Cheers!

  13. I¡¦m not positive the place you are getting your info, but good topic. I needs to spend a while studying much more or figuring out more. Thanks for excellent info I was looking for this info for my mission.

  14. Greetings! I’ve been reading your blog for a while now andfinally got the courage to go ahead and give you a shout out from Austin Texas!Just wanted to say keep up the excellent job!

  15. I will right away grab your rss as I can’t find your email subscription link or e-newsletter service. Do you have any? Please allow me realize so that I may subscribe. Thanks.

  16. Howdy! I could have sworn I’ve been to this blog beforebut after checking through some of the post I realized it’s newto me. Anyways, I’m definitely glad I found it and I’ll be book-markingand checking back frequently!

  17. When I originally commented I clicked the “Notify me when new comments are added” checkbox and noweach time a comment is added I get several emails with the same comment.Is there any way you can remove me from that service?Cheers!

  18. When someone writes an post he/she keeps the image of a user in his/hermind that how a user can understand it. Thus that’s why this post is perfect.Thanks!

  19. I wanted to thank you for this wonderful read!! I definitely loved every bit of it. I have got you book marked to look at new things you postÖ

  20. What’s Happening i’m new to this, I stumbled upon this I have foundIt positively helpful and it has helped me outloads. I’m hoping to give a contribution & assist other users likeits helped me. Good job.

  21. I do not even understand how I finished up right here, but I believed this submit used to be great. I do not know who you might be however definitely you are going to a well-known blogger for those who aren’t already 😉 Cheers!

  22. I do not even know how I ended up here, but I thought this post was great.I don’t know who you are but definitely you’re going to a famous bloggerif you aren’t already 😉 Cheers!

  23. What’s up i am kavin, its my first occasion to commenting anywhere, when iread this piece of writing i thought i could also make comment due to this sensible paragraph.

  24. Hi just wanted to give you a brief heads up and let you know a few of the images aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome.

  25. I will immediately clutch your rss feedas I can’t in finding your e-mail subscription link or e-newsletterservice. Do you have any? Please allow me recognize in order that I may just subscribe.Thanks.

  26. Thank you for sharing your info. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.

  27. Thank you for another magnificent article. Where else may just anybody get that kind of info in such an ideal approach of writing? I have a presentation subsequent week, and I’m at the look for such info.

  28. Have you ever heard of second life (sl for short). It is essentially a online game where you can do anything you want. Second life is literally my second life (pun intended lol). If you want to see more you can see these sl authors and blogs

  29. I want to to thank you for this very good read!! I absolutely loved every bit of it. I’ve got you book-marked to look at new stuff you postÖ

  30. Thanks , I have recently been looking for info about this topic for ages and yours is the greatest I have discovered till now. But, what about the conclusion? Are you sure about the source?

  31. Great post. I was checking continuously this blog and I’m impressed! Extremely helpful information specifically the last part 🙂 I care for such info much. I was looking for this certain info for a long time. Thank you and best of luck.

  32. I will immediately grasp your rss as I can’t to find your e-mail subscription link or newsletter service. Do you have any? Kindly allow me understand so that I could subscribe. Thanks.

  33. Nice post. I was checking continuously this blog and I am impressed! Very helpful information specifically the last part 🙂 I care for such info much. I was seeking this particular information for a very long time. Thank you and best of luck.

  34. Nice post. I was checking constantly this blog and I am impressed!Very useful info particularly the last part 🙂 I care for such information much. I was looking for this certain information fora very long time. Thank you and good luck.

  35. ช่วงต้นผมว่าเว็บไหนก็แบบเดียวกัน เนื่องจากว่าเข้าไปก็พบเกมเดิมๆแม้เอาเข้าจริงๆมันแตกต่างขอรับ ยิ่งเว็บไซต์ไหนที่เวลาฝากถอนจะต้องผ่านข้าราชการอันนี้ผมเกลียดสุดเลย เสียเวล่ำเวลา ส่วนตัวผมว่า UFABET ดีสุดเลยนะครับผม เค้าใช้ระบบอัตโนมัติ

  36. Thanks for every other magnificent post. Where else could anyone get that type of information in such a perfect manner of writing? I’ve a presentation subsequent week, and I am on the search for such information.

  37. Thanks for finally writing about > RDC-Haut Katanga:Toutes les femmes détenues à la prison de la kassapasont violées chaque jour(Jean-Claude Muyambo)– Coulisses.net weight regain

  38. Generally I don’t read post on blogs, but I would liketo say that this write-up very compelled meto take a look at and do so! Your writing style has been amazed me.Thank you, very great post.

  39. Hey! This is my first comment here so I just wanted tto give a quick shout out and say I truly enjoyreading through your articles. Appreciate it!

  40. Excellent post. I was checking constantly this blog and I’m impressed! Extremely useful information particularly the last part 🙂 I care for such info a lot. I was looking for this particular info for a very long time. Thank you and good luck.

  41. You can certainly see your expertise within the work you write. The arena hopes for more passionate writers such as you who aren’t afraid to mention how they believe. At all times follow your heart.

  42. Heya i am foг tһe fіrst time hеrе. І foսnd thіs boardand Ӏ fin It гeally helpful & iit helpedmе out mսch. I am hoping to provide onne tһing agɑin and aid others sjch aѕ yoou helped mе.Check out my pɑge; pkv games qq

  43. Wһen someone wrіtes an article he/she қeeps the рlan ofa user in hіs/her mind tһat how a user can be aᴡare of it.Therеfore that’s wһy this post is outstdanding.Thanks!

  44. Hello, you used to write fantastic, but the last few posts have been kinda boring… I miss your super writings. Past few posts are just a little bit out of track! come on!

  45. I do trust all the ideas you have presented to your post. They’re really convincing and can definitely work. Still, the posts are too quick for novices. May you please lengthen them a bit from next time? Thank you for the post.

  46. An intriguing discussion is worth comment. There’s no doubt that that you need to publish more about this issue, it may not be a taboo matter but generally folks don’t discuss such subjects. To the next! Kind regards!!

  47. I’d must verify with you here. Which isn’t something I normally do! I get pleasure from reading a post that will make individuals think. Also, thanks for allowing me to comment!

  48. I’m not sure where you are getting your information, but great topic. I needs to spend some time learning much more or understanding more. Thanks for excellent info I was looking for this information for my mission.

  49. I appreciate, result in I discovered just what I used to be takinga look for. You have ended my 4 day long hunt! God Bless you man. Have anice day. Bye

  50. Aw, this was an exceptionally nice post. Taking the time and actual effort to produce a great articleÖ but what can I sayÖ I procrastinate a lot and never seem to get nearly anything done.

  51. My family always say that I am wasting my time here at net, but I know I am getting know-how everyday by reading thes fastidious articles or reviews.

  52. hello!,I really like your writing so much! percentagewe be in contact more approximately your article on AOL?I need an expert on this space to unravel my problem.May be that is you! Looking ahead to look you.

  53. Hey, you used to write fantastic, but the last few posts have been kinda boring?K I miss your super writings. Past several posts are just a little bit out of track! come on!

  54. Hi my friend! I wish to say that this article is awesome, great written and comewith approximately all vital infos. I’d like to peer extraposts like this .

  55. What’s Going down i’m new to this, I stumbled upon this I havefound It absolutely helpful and it has aided me out loads.I am hoping to contribute & help different users like its aided me.Good job.

  56. Good day! This is my first visit to your blog! We are a collection of volunteers and starting a new initiative in a community in the same niche. Your blog provided us beneficial information to work on. You have done a outstanding job!

  57. I will immediately seize your rss as I can’t find your email subscription hyperlink or e-newsletterservice. Do you have any? Kindly let me recognise so that I may justsubscribe. Thanks.

  58. You could certainly see your expertise in the paintings you write. The arena hopes for even more passionate writers like you who aren’t afraid to say how they believe. All the time follow your heart.

  59. I do accept as true with all the concepts you’ve offered in your post.They are really convincing and can definitely work.Nonetheless, the posts are very brief for newbies.May you please prolong them a bit from next time? Thanks forthe post.

  60. Hello! This is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done a wonderful job!

  61. This is a good tip particularly to those new to the blogosphere. Short but very accurate infoÖ Thank you for sharing this one. A must read post!

  62. Wow! This can be one particular of the most beneficial blogs We have ever arrive across on this subject. Basically Wonderful. I am also an expert in this topic so I can understand your hard work.

  63. Howdy! This post could not be written any better! Going through this article reminds me of my previous roommate! He continually kept preaching about this. I’ll send this post to him. Fairly certain he will have a great read. Thanks for sharing!

  64. fantastic issues altogether, you just gained a brand new reader. What could you recommend about your submit that you made some days in the past? Any positive?

  65. I quite like reading through an article that will make men and women think. Also, thanks for allowing for me to comment!

  66. Your way of explaining all in this article is truly nice, every one beable to effortlessly be aware of it, Thanks a lot.

  67. I’m retired tylenol dose for breastfeeding mom “Epicephala moths have an excellent ability to handle olfactory information which other insects do not have, supporting the highly specific interaction and complicated behaviours,” said Dr Okamoto.

  68. Heya i’m for the primary time here. I found this board and I in finding It truly useful & it helped me out much. I’m hoping to give something again and aid others such as you helped me.

  69. Hello! I’ve been following your blog for a while now and finally got the courage to go ahead and give you a shout out from Kingwood Texas! Just wanted to mention keep up the good work!browse around here

  70. An interesting dialogue is worth comment. I think that you need to write extra on this subject, it won’t be a taboo subject but usually people are not enough to talk on such topics. To the next. Cheers

  71. I enjoyed your post. Thank you. It’s like you read my thoughts! Thanks for writing this. Your article has proven useful to me.

  72. I like the helpful information you provide in your articles. I?ll bookmark your blog and check again here frequently. I am quite sure I?ll learn many new stuff right here! Best of luck for the next!

  73. Aw, this was a really nice post. In thought I wish to put in writing like this additionally – taking time and precise effort to make an excellent article… however what can I say… I procrastinate alot and not at all seem to get one thing done.

  74. I read this piece of writing fully concerning the comparison of most up-to-date and earlier technologies,it’s remarkable article.

  75. It’s actually a great and helpful piece of information. I’m satisfied that you simply shared this helpful infowith us. Please stay us up to date like this.Thank you for sharing.

  76. Thanks. Excellent information.things to write an argumentative essay on steps to writing a thesis statement article writer

Leave a Reply

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