Implementing Facebook account authentication is very popular these days. ⁤⁤It is easy and powerful method for user authentication, Facebook account authentication takes less effort from user for registration or login on your system. ⁤⁤there is no need for the user to remember the username and password.

Php Facebook Login - Implement  Facebook Account Login in PHP Application

Table Of Content

1 Prerequisites

1.) PHP version of 7.4>
2.) Composer
3.) Facebook SDK

2 Introduction

In this article, We are going to see how to implementation Facebook account authentication to your PHP application. We’ll be using Facebook SDK.

3 Create Project Folder "facebook-signin-app"

Create Project Folder "facebook-signin-app" in root directory store all project files

4 Install Facebook SDK

First, make sure your computer has a composer.
Use the following command to install Facebook SDK via Composer.

composer require facebook/graph-sdk

This command will download the Facebook sdk and add it to your project.

5 Create Facebook App Credentials

5.1 Login into Facebook Developers Portal

If you have Facebook Developer Account Go to https://developers.facebook.com/, else you can easily create one directly from the Facebook Developers Portal.

5.2 Create a Facebook App

Click on "Create App" Button and follow the prompts to create a new Facebook App
Facebook Create App
Create an App in the Facebook/Meta Admin


5.3 Configure OAuth Settings

In Following Screen select "Authenticate and request data from users with Facebook Login" Option Facebook Add Use Case
Facebook Login Type

Fill the Details of the App in following Screen and Press " Create App " Button Facebook App Details

In the Facebook App dashboard, navigate to " App Settings" Menu and then "Basic" Facebook App Settings

Now Copy App Id and App Secret to update in .env file and enter the website Domain URL in App Domains field, Again Scroll down in same screen to "Add Platform" details then Select Website and update Site URL. Facebook App Add Platform

Facebook App Site URL

5.4 Update App Information

Now go to "Use Cases" tab then click "Customize" Button and select "settings" option Facebook Use Cases Customize

Facebook App Use Case Setting

Now fill the authorised redirect URIs. This is the URI that we will use to redirect user after they choose their Facebook account to login to our web. For example here I use http://127.0.0.1:8000/callback/facebook for the callback URI..
Facebook App Setting

Client OAuth Settings Add OAuth Redirect URI in the Facebook/Meta Admin.

6 Configure Facebook App Credentials(config.php)

Insert the App ID and App Secret key and redirect URI into the config.php file, Which we obtained from previous step FACEBOOK_APP_ID and FACEBOOK_APP_SECRET. Additionally, include a new key in the config.php file called FACEBOOK_REDIRECT_URI and populate it with the callback URI used in the Facebook / Meta Admin.

define('FACEBOOK_APP_ID', 'YOUR_APP_ID');   
define('FACEBOOK_APP_SECRET', 'YOUR_APP_SECRET');   
define('FACEBOOK_REDIRECT_URI', 'http://localhost/facebook-signin-app/facebook-callback.php');   

7 Create Login Page - login.php

Create a simple login page (login.php) that includes a "Login with Facebook" button: facebook-signin-app/login.php

<?php
require_once 'vendor/autoload.php';
include('config.php');


$fb = new \Facebook\Facebook([
  'app_id' => FACEBOOK_APP_ID,
  'app_secret' => YOUR_APP_SECRET,
  'default_graph_version' => 'v12.0',
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl(FACEBOOK_REDIRECT_URI, $permissions);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login with Facebook</title>
</head>
<body>
    <h1>Login with Facebook</h1>
    <a href="<?= htmlspecialchars($loginUrl) ?>">Login with Facebook</a>
</body>
</html>


8 Create Facebook Callback Page - facebook-callback.php

Create a file (facebook-callback.php) to handle the callback from Facebook after authentication facebook-signin-app/facebook-callback.php

<?php
require_once 'vendor/autoload.php';
session_start();
include('config.php');


$fb = new \Facebook\Facebook([
  'app_id' => FACEBOOK_APP_ID,
  'app_secret' => YOUR_APP_SECRET,
  'default_graph_version' => 'v12.0',
]);

$helper = $fb->getRedirectLoginHelper();

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;
}

// Logged in
echo '

Access Token

'; var_dump($accessToken->getValue()); // Getting user's info $oAuth2Client = $fb->getOAuth2Client(); $tokenMetadata = $oAuth2Client->debugToken($accessToken); $tokenMetadata->validateAppId(FACEBOOK_APP_ID); $tokenMetadata->validateExpiration(); if (!$accessToken->isLongLived()) { try { $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken); } catch (Facebook\Exceptions\FacebookSDKException $e) { echo "

Error getting long-lived access token: " . $e->getMessage() . "

"; exit; } } $_SESSION['fb_access_token'] = (string) $accessToken; try { // Returns a `Facebook\GraphNodes\GraphUser` object $response = $fb->get('/me?fields=id,name,email', $accessToken); } catch(Facebook\Exceptions\FacebookResponseException $e) { echo 'Graph returned an error: ' . $e->getMessage(); exit; } catch(Facebook\Exceptions\FacebookSDKException $e) { echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } $user = $response->getGraphUser(); // Store user data in session or database $_SESSION['id'] = $user['id']; $_SESSION['name'] = $user['name']; $_SESSION['email'] = $user['email']; header('Location: dashboard.php'); exit;

9 Create Dashboard - dashboard.php

Create a simple secured page (dashboard.php) that only logged-in users can access: facebook-signin-app/dashboard.php

<?php
session_start();
if (!isset($_SESSION['id'])) {
    header('Location: login.php');
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
</head>
<body>
    <h5>Facebook Account Details</h5>
    <p>Facebook ID: <?= htmlspecialchars($_SESSION['id']); ?></p>
    <p>Name: <?= htmlspecialchars($_SESSION['name']); ?></p>
    <p>Your email: <?= htmlspecialchars($_SESSION['email']); ?></p>
    <p><a href="logout.php">Logout</a></p>
</body>
</html>

10 Implement Logout Functionality

Create a logout page (logout.php) to destroy the session and log the user out: facebook-signin-app/logout.php

<?php
session_start();
session_destroy();
header('Location: login.php');
exit();

11 Folder Structure

12 Run Web Server to Test the App

Visit the URL http://localhost/facebook-signin-app/login.php

13 Conclusion

That’s all we need to do.
This guide should help you integrate Facebook Login in your PHP application

Tags