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
That is going to do it for this post! Leave any comments/questions/concerns below and thanks for stopping by the blog!
Hello there! I simply wish to offer you a big thumbs up for the excellent info you’ve got right here on this post. I’ll be returning to your blog for more soon.
I’m extremely pleased to discover this website. I want to to thank you for ones time for this fantastic read!! I definitely savored every part of it and i also have you saved to fav to check out new things in your web site.
I couldn’t refrain from commenting. Perfectly written!
It’s nearly impossible to find knowledgeable people on this subject, however, you sound like you know what you’re talking about! Thanks
You are so cool! I don’t suppose I’ve truly read through something like this before. So wonderful to discover somebody with a few original thoughts on this issue. Really.. many thanks for starting this up. This website is one thing that is required on the web, someone with a little originality.
I have to thank you for the efforts you’ve put in writing this website. I’m hoping to check out the same high-grade blog posts from you later on as well. In fact, your creative writing abilities has encouraged me to get my own, personal blog now 😉
Hi, I do think this is a great site. I stumbledupon it 😉 I will come back yet again since I book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to help others.
Great post. I will be going through many of these issues as well..
Hi, I do think this is a great web site. I stumbledupon it 😉 I’m going to return yet again since i have book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to help other people.
I couldn’t refrain from commenting. Very well written.
I was able to find good information from your content.
Hi there! This article couldn’t be written much better! Going through this article reminds me of my previous roommate! He constantly kept talking about this. I’ll send this information to him. Pretty sure he’ll have a good read. Thank you for sharing!
You’re so cool! I don’t suppose I’ve truly read through anything like that before. So nice to discover someone with genuine thoughts on this subject. Really.. thanks for starting this up. This site is something that is needed on the internet, someone with a little originality.
Aw, this was an incredibly nice post. Taking a few minutes and actual effort to make a good article… but what can I say… I put things off a lot and don’t seem to get anything done.
This excellent website definitely has all the info I needed about this subject and didn’t know who to ask.
Having read this I believed it was very informative. I appreciate you taking the time and effort to put this content together. I once again find myself spending a lot of time both reading and commenting. But so what, it was still worthwhile.
This blog was… how do you say it? Relevant!! Finally I have found something which helped me. Many thanks.
Great article! We will be linking to this particularly great post on our website. Keep up the good writing.
There’s definately a lot to know about this subject. I like all of the points you have made.
Everything is very open with a very clear explanation of the issues. It was really informative. Your site is useful. Thank you for sharing!
Everything is very open with a very clear explanation of the issues. It was truly informative. Your website is very helpful. Thank you for sharing.
You ought to be a part of a contest for one of the best sites on the web. I am going to highly recommend this blog!
May I just say what a relief to uncover somebody that genuinely knows what they’re talking about on the internet. You definitely know how to bring an issue to light and make it important. A lot more people need to read this and understand this side of your story. I can’t believe you are not more popular given that you most certainly have the gift.
I was able to find good advice from your content.
I’m pretty pleased to discover this page. I need to to thank you for your time for this fantastic read!! I definitely enjoyed every little bit of it and I have you book-marked to see new things on your blog.
Having read this I thought it was very enlightening. I appreciate you finding the time and effort to put this content together. I once again find myself personally spending a lot of time both reading and posting comments. But so what, it was still worthwhile.
Having read this I believed it was extremely enlightening. I appreciate you finding the time and effort to put this article together. I once again find myself personally spending a significant amount of time both reading and leaving comments. But so what, it was still worthwhile.
Good post. I learn something new and challenging on websites I stumbleupon every day. It will always be interesting to read content from other writers and use a little something from other sites.
Everyone loves it when folks get together and share views. Great site, continue the good work.
Can I simply say what a comfort to discover someone that truly knows what they are discussing online. You definitely know how to bring a problem to light and make it important. A lot more people really need to look at this and understand this side of your story. I was surprised you’re not more popular since you certainly possess the gift.
You need to be a part of a contest for one of the most useful sites online. I am going to highly recommend this web site!
I could not refrain from commenting. Exceptionally well written.
Oh my goodness! Impressive article dude! Thank you so much, However I am going through difficulties with your RSS. I don’t know the reason why I cannot subscribe to it. Is there anyone else getting the same RSS problems? Anyone that knows the answer can you kindly respond? Thanx!
Great information. Lucky me I found your blog by chance (stumbleupon). I have saved as a favorite for later!
Howdy! This blog post could not be written any better! Looking through this post reminds me of my previous roommate! He always kept talking about this. I’ll forward this article to him. Pretty sure he’ll have a very good read. I appreciate you for sharing!
Howdy! I simply would like to give you a big thumbs up for your great information you have right here on this post. I will be coming back to your web site for more soon.