Last updated on November 20, 2017
Nowadays social media login are everywhere and users are not interested in filling a lengthy form to register. Most of the popular websites are already providing Facebook login feature. So in this post, I would like to show you, Facebook login integration steps using PHP.
To get started with the latest version of Facebook SDK v5.X, make sure your system meets the following requirements.
PHP version should be 5.4 or greater.
The mbstring
extension should be enabled.
This post assumes that you have prior knowledge of the composer. So let’s get started.
Step 1: Goto https://developers.facebook.com/apps/ and Click Add a New App .
» Choose Website
» Choose Name for you App and Click Create New Facebook App ID
» Choose a category for you App and click Create App ID
» Now Click Skip Quick Test
Step 2 Under settings, Provide values for App domain ( Eg: arjunphp.com ) and Contact Email and click Add Platform.
Provide Values for Site URL and Mobile site URl ( Optional )
Step 3 By default your app enabled for sandbox mode you need to change it to live. To make it live, click on Status & Review tab and click the button to make you App live.
That’s it App settings done now come to the coding.
Step 4 The Facebook PHP SDK can be installed with Composer. Run this command:
composer require facebook/graph-sdk
Step 5:
FB_APP_ID, 'app_secret' => FB_APP_SECRET, 'default_graph_version' => FB_APP_GRAPH_VERSION, //'default_access_token' => '{access-token}', // optional ]); $helper = $fb->getRedirectLoginHelper(); if(!$_GET['code']) { $permissions = ['email', 'user_posts']; // optional $loginUrl = $helper->getLoginUrl(FB_APP_CALLBACK_URL, $permissions); echo 'Log in with Facebook!'; } else { try { // get user access token $accessToken = $helper->getAccessToken(); // store access token in the user session. $_SESSION['facebook_access_token'] = (string) $accessToken; } catch(Facebook\Exceptions\FacebookSDKException $e) { // There was an error communicating with Graph echo $e->getMessage(); exit; } if($_SESSION['facebook_access_token']) { // User authenticated your app! // Save the access token to a session and redirect try { // Get the \Facebook\GraphNodes\GraphUser object for the current user. // If you provided a 'default_access_token', the '{access-token}' is optional. $response = $fb->get('/me?fields=id,name,email', $_SESSION['facebook_access_token']); // get current user info object $me = $response->getGraphUser(); // echo current user name and email echo 'Logged in as ' . $me->getName() .' '. $me->getEmail(); } 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; } } }