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!
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.
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!
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.
I am so grateful for your blog.Much thanks again. Want more.
Absolutely indited content , thanks for entropy.
Thanks! I was afraid the orange wouldn’t look good in a photo, but it really looks great! 🙂
I have read so many posts on the topic of the blogger lovers except this articleis actually a nice piece of writing, keep it up.
Awesome blog article.Much thanks again. Really Cool.
Very neat blog post.Thanks Again. Will read on…
This is one awesome blog. Really Great.
I value the post. Will read on…
Very neat article post.Really looking forward to read more. Really Great.
Wow, great blog.Much thanks again. Will read on…
Thank you ever so for you blog.Thanks Again. Great.
Hello friends, pleasant piece of writing and nice argumentscommented here, I am actually enjoying by these.Also visit my blog: Mili-Tac Watch
fantastic issues altogether, you just received a emblem new reader.What would you suggest about your post that you just made a few days ago?Any certain?
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.
I am so grateful for your post.Thanks Again. Cool.
kamagra pills: erectile dysfunction pills ed pills
Looking forward to reading more. Great article.Really thank you! Great.
This is one awesome article.Really looking forward to read more. Cool.
turkey pharmacy online italian pharmacy online
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.
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!!
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.
Your mode of describing everything in this article is truly pleasant, every one be able to easily know it, Thanks a lot.
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?
Enjoyed every bit of your blog article. Really Great.
Verry gpod post. I absolutely apprecate thiss site.
Thanks!
Everyone loves what you guys tend to be up too.This sort of clever work and exposure! Keep up the superb works guysI’ve incorporated you guys to our blogroll.
I truly appreciate this article post.Really thank you! Will read on…
slots free slots games free vegas slots online
When you have a dream, you’ve got to grab it and never let go.’ By Carol Burnett
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?
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.
vulkanslots net вулкан slots игровые
Thanks so much for the blog.Really thank you!
Enjoyed every bit of your blog post. Really Cool.
Pretty! This has been an exdtremely wonderful post.Thanbks for providing thisinfo.
I think this is a real great blog article.Really thank you! Keep writing.