Facebook login example is very common and easy to use. Nowadays most of the users do not want to fill long registration forms on websites. That is why most of the developers provide a facebook login button on their websites.
If the user has a facebook account they can log in to the website with FB account. PHP is a very powerful language and Facebook also provides PHP SDK to access facebook API.
File Structure and facebook PHP SDK Class
Before starting further, you need to understand the file structure. Create bellow listed files and download facebook PHP SDK class form here .
index.php welcome.php fb-callback.php fb-config.php logout.php
Create an app on Facebook
To create a facebook login button you need to do the following steps. So, The below image explains the menu of the app dashboard.
FB APP DASHBOARD
Create an app on facebook. (Click here to create FB App )After creating the app you need to add a product on the app dashboard that defines the app scope select Facebook Login . In the app, the dashboard goes to the settings there are two menus Basic , Advanced . Finally, you need to set the callback URL into the app go to the product ->settings and enter you a callback URL and save changes. Probably you need to change the status of your app to live .
Furthermore, the below image shows where you set the callback URL. And remember Client and Web OAuth login must be enabled.
After setting up the app follow the below process to create a login button. Into the basic settings of your app, you will see the App ID and App Secret copy these ids and replace them in the fb-config.php file as below.
<?php
session_start();
include_once('php-graph-sdk-5.x/src/Facebook/autoload.php');
$fb = new Facebook\Facebook(array(
'app_id' => '{app-id}', // Replace with your app id
'app_secret' => '{app-secret}', // Replace with your app secret
'default_graph_version' => 'v3.2',
));
$helper = $fb->getRedirectLoginHelper();
?>
Remember : you must need to include this file into all files at the top of the page. Without this file, you are not able to access FB PHP SDK.
Now in the index.php, you need to paste below code just after the fb-config.php includes. The below code snippet creates a Login URL with email permission . This example is in bootstrap4 you can use URL on structure.
<?php
$permissions = array('email'); // Optional permissions
$loginUrl = $helper->getLoginUrl('https://learncodeweb.com/demo/php/login-with-facebook-using-php-sdk/fb-callback.php', $permissions);
?>
<form method="post">
<div class="form-group">
<label>Login ID</label>
<input type="text" class="form-control" name="userId" placeholder="User ID">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="userPassword" placeholder="User Password">
</div>
<div class="form-group">
<button type="button" class="btn btn-danger btn-block" value="Login"><i class="fa fa-sign-in-alt"></i> Login</button>
</div>
<div class="form-group">
<a href="<?php echo htmlspecialchars($loginUrl); ?>" class="btn btn-primary btn-block"><i class="fab fa-facebook-square"></i> Log in with Facebook!</a>
</div>
</form>
Now on the callback page, we check the user and set session if the user has an account on Facebook. Open the fb-callback.php page and paste the below code in it.
<?php
include_once('fb-config.php');
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();
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';
}
exit;
}
if(!$accessToken->isLongLived()){
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $e->getMessage() . "</p>\n\n";
exit;
}
}
//$fb->setDefaultAccessToken($accessToken);
# These will fall back to the default access token
$res = $fb->get('/me',$accessToken->getValue());
$fbUser = $res->getDecodedBody();
$resImg = $fb->get('/me/picture?type=large&redirect=false',$accessToken->getValue());
$picture = $resImg->getGraphObject();
$_SESSION['fbUserId'] = $fbUser['id'];
$_SESSION['fbUserName'] = $fbUser['name'];
$_SESSION['fbAccessToken'] = $accessToken->getValue();
header('Location: welcome.php');
exit;
?>
On the welcome page, you can access the login user data with the help of $_SESSION .
If you want to logout the user from everywhere I mean of FB then you need to use the below code. Because of the below code user will logout from the FB and on logout.php page you unset the FB sessions that your start on callback page. Or if you do not want to logout the user form FB you just sent the user to logout.php where you unset the FB sessions.
$logoutUrl = $helper->getLogoutUrl($_SESSION['fbAccessToken'], 'https://learncodeweb.com/demo/php/login-with-facebook-using-php-sdk/logout.php');
echo '<a href="'.$logoutUrl.'" class="btn btn-lg btn-danger"><i class="fa fa-fw fa-power-off"></i> Logout</a>';
Open the logout.php page and paste the below code to unset the session.
<?php
include_once('fb-config.php');
session_destroy();
unset($_SESSION['fbUserId']);
unset($_SESSION['fbUserName']);
unset($_SESSION['fbAccessToken']);
header('location: https://learncodeweb.com/demo/php/login-with-facebook-using-php-sdk/index.php');
exit;
?>