Login with Social Media accounts have picked up a lot of interest in the recent times as users get lazier by the day and don’t want to manage several accounts at every website they visit. So if you have website with login system, or are in the process of making one, you might as well add Login with Facebook and maybe Login with Google (Tutorial coming soon) as well while you’re at it.
There are several tutorials available for the task but here’s how this one differs from the rest:
- I assume you already have a basic login system in place that users can use to register and login, old fashioned way.
- This tutorial is not entirely PHP, rather uses Javascript to make UI better for the user by opening a popup for asking permission instead of another page which, to me, feels rather abrupt.
So let’s get into it.
1. Add an element to trigger Facebook login
<a href="#" id="fb-login" class="btn btn-facebook"><i class="fa fa-facebook"></i> Sign in using Facebook</a>
You can have any element to trigger the login, using a tag or img or pretty much anything, as we use jQuery to trigger the click.
2. The Javascript
First we load the Facebook’s Javascript Library then initialize the app to get ready for login. I add the script in footer.php page because that way I can disable it when the user has logged in.
<?php if(!isset($_SESSION['user'])){ ?> <script> // Load the SDK asynchronously (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <?php } ?>
The library is quite heavy in my opinion so if user has logged in, he doesn’t need it. We’ll skip it in that case. Next, in a js file or before the closing “body” tag add the following javascript:
window.fbAsyncInit = function() { FB.init({ appId : 'YOUR_APP_ID', cookie : true, xfbml : true, version : 'v2.8' // Use whatever version is latest at this time }); }; function fb_login(){ FB.login(function(response){ var grantedScopes = response.authResponse.grantedScopes; if (response.status === 'connected') { if(grantedScopes.indexOf('email') != -1 || grantedScopes.indexOf('contact_email') != -1){ window.location.replace('includes/fblogin/fb-callback.php'); } else { FB.api("/me/permissions", "delete", function(response){ alert('Authorization Failed. Email Required.'); }); } } }, { scope: 'public_profile, email', return_scopes: true }); }; $('#fb-login').on('click', function(e){ e.preventDefault(); fb_login(); });
Pretty simple, right? We initialize the library, create a function that handles login and call the function when our element is clicked on. The fb_login() is the function that sends our user to the php page which in our case is located at www.domain.com/includes/fblogin/fb-callback.php. Edit this to match your callback file which we’ll make next.
When the user clicks the button, a popup window will display which will ask for user to login to his Facebook account if she’s not already logged in. If she is, Facebook will ask the user to provide the permissions to your App that you requested, in this case, Public profile and email. If she provides these permissions Facebook will send that information to your callback file.
And I almost forgot, at this point you should have created an app. If not, go to developers.facebook.com and create one, get it’s Id and enter above in your javascript code.
3. Call me back?
No, its called callback. If the user has provided all the required fields, Facebook will send the user’s details on your callback file. This file should additionally include the Facebook SDK for PHP. I’m using v5 in this tutorial and it’s saved in www.domain.com/includes/fblogin/src/ . Here’s how the fb-callback.php looks like
<?php require '../config.php'; require_once 'src/facebook-sdk-v5/autoload.php'; $fb = new Facebook\Facebook([ 'app_id' => 'YOUR_APP_ID', 'app_secret' => 'YOUR_APP_SECRET', 'default_graph_version' => 'v2.8', ]); $helper = $fb->getJavaScriptHelper(); try { $accessToken = $helper->getAccessToken(); } catch(Facebook\Exceptions\FacebookResponseException $e) { // When Graph returns an error echo 'Graph returned an error: ' . $e->getMessage(); } catch(Facebook\Exceptions\FacebookSDKException $e) { // When validation fails or other local issues echo 'Facebook SDK returned an error: ' . $e->getMessage(); } if (isset($accessToken)) { $fb->setDefaultAccessToken($accessToken); try { $requestProfile = $fb->get("/me?fields=name,email,picture"); $profile = $requestProfile->getGraphNode()->asArray(); } catch(Facebook\Exceptions\FacebookResponseException $e) { // When Graph returns an error echo 'Graph returned an error: ' . $e->getMessage(); } catch(Facebook\Exceptions\FacebookSDKException $e) { // When validation fails or other local issues echo 'Facebook SDK returned an error: ' . $e->getMessage(); } if(isset($profile['email'])){ $profileSet['token'] = $profile['id']; $profileSet['name'] = $profile['name']; $profileSet['email'] = $profile['email']; $profileSet['source'] = 'facebook'; $profileSet['avatar'] = '//graph.facebook.com/'.$profile['id'].'/picture?type=large'; // Log user in socialLogin($profileSet, 1, 'facebook'); } else { $_SESSION['msg']['type'] = 'error'; $_SESSION['msg']['content'] = 'Authentication Failed. Email address is Required'; } if(isset($_SESSION['redirect'])){ header('location:'.$_SESSION['redirect']); unset($_SESSION['redirect']); } else { header('location: '.SITE_URL); } exit; } else { echo "Unauthorized access!!!"; exit; } ?>
This is the file that’ll require customization on your part. I’ll explain my code:
- First I include my config file which contains database access and global constants and stuff; autoload.php which loads the Facebook PHP SDK into the document.
- We initialize an object that holds your App configuration. Use the same App Id as you did before and get the Secret in the same place you got your App Id from.
- Next we use Facebook’s code to call the Graph API to request the user’s information via the token that we’ve generated. We save this information in an array $profile . Notice the javascript was only to obtain permission to call this API on the behalf of your user.
- Under the line if(isset($profile[’email’])){ will be your code. At this point you have the required details in the $profile array. I create another array $profileSet which is just to reorganize the data that I have and ignore what I don’t need as there’ll be a lot more stuff in the previous array that you may or may not need, along with a small profile picture. But notice how I use the Graph API to get a better quality image using the user’s id. I use a function socialLogin to sign up/login the user but you can do it however you wish. This function is part of my
bullet-proofnuke proof login system. Would you like a tutorial for that? Let me know in the comments.At the very least, you have to add certain information to your $_SESSION array to keep him logged in.
- Redirect the user back where he came from or to the home page. You have logged a user in successfully.
4. Logging Out
If you have to log a user out, you don’t need to do anything special, just delete their session and cookies data. There’s no need to log user out from facebook on your app but if you must, you can trigger this function before logging out the user from php.
FB.logout(function(response) { // Person is now logged out });
Keep in mind though that you’ll have to keep the Facebook Javascript SDK loaded at all times which we aren’t doing in this example.
2 thoughts to “Add Facebook Login to a PHP Website”
Thanks so much, very helpful!
Pingback: 404 Not Found - BWD MEDIA Blog