Login with Facebook using PHP SDK
All website require login/signup using the social app’s like Facebook, Google, Twitter and many more, Some user did not like to create new login details in your website so we require to add social login. we discuss how to use Facebook PHP SDK for login user through there facebook account.
We need to create Facebook APP for it, how to create Facebook APP
Download PHP SDK from git and include in you index.php file.
require_once 'php-graph-sdk-5.4/src/Facebook/autoload.php';
Create object of Facebook and set options to start connecting. Set app id and app secret into options
$appId = 'Your_Appid'; $appSecret = 'Your_App_Secret';
$fb = new Facebook\Facebook([ 'app_id' => $appId, 'app_secret' => $appSecret, 'default_graph_version' => 'v2.6', 'default_access_token' => $appId."|".$appSecret ]); $helper = $fb->getRedirectLoginHelper(); $permissions = ['public_profile']; $loginUrl = $helper->getLoginUrl('http://yourdomain.com/login.php', $permissions); echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';
How to set facebook permissions
Now create new php file named login.php and do same like we done in index.php
require_once 'php-graph-sdk-5.4/src/Facebook/autoload.php'; $appId = 'Your_Appid'; $appSecret = 'Your_App_Secret'; $fb = new Facebook\Facebook([ 'app_id' => $appId, 'app_secret' => $appSecret, 'default_graph_version' => 'v2.6', 'default_access_token' => $appId."|".$appSecret ]); $helper = $fb->getRedirectLoginHelper(); if (isset($_GET['state'])) { $helper->getPersistentDataHandler()->set('state', $_GET['state']); } try { $accessToken = $helper->getAccessToken(); } 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(); redirect('http://yourdomain.com/index.php'); exit; } if (! isset($accessToken)) { if ($helper->getError()) { header('HTTP/1.0 401 Unauthorized'); echo "Error: " . $helper->getError() . "\n"; echo "Error Code: " . $helper->getErrorCode() . "\n"; echo "Error Reason: " . $helper->getErrorReason() . "\n"; echo "Error Description: " . $helper->getErrorDescription() . "\n"; } else { header('HTTP/1.0 400 Bad Request'); echo 'Bad request'; } redirect('http://yourdomain.com/index.php'); exit; } $oAuth2Client = $fb->getOAuth2Client(); $tokenMetadata = $oAuth2Client->debugToken($accessToken); $tokenMetadata->validateAppId($appId); // Replace {app-id} with your app id $tokenMetadata->validateExpiration();
Access token generated and authenticate with Facebook. and now we able to get user personal detail.
See: How to get Facebook user detail.