How to Implement Facebook Login in PHP (Quick Overview)

             

Implementing Facebook Login in PHP uses OAuth 2.0 to let users sign in securely with their Facebook account — no custom forms needed. The process relies on the maintained Facebook Graph SDK for PHP (via Composer), which handles token exchange, user data retrieval, and session management.

Core flow in minutes:

  1. Create a Facebook app in the Meta Developer Dashboard and note your App ID + Secret.
  2. Install the SDK: composer require facebook/graph-sdk (use a community-maintained fork like joelbutcher's for PHP 8+ compatibility in 2026).
  3. Generate a login link with requested permissions (e.g., email).
  4. Handle the redirect callback: exchange code for access token, fetch user profile (/me?fields=id,name,email), and store in session.
  5. Protect pages (like dashboard) by checking the session; add logout to clear it.

This server-side approach works great for pure PHP apps. Use the latest Graph API version (currently v24.0 as of January 2026) in your config for best compatibility and features. Follow the steps below for full code and setup — you can have it running in under 30 minutes!



Facebook Login in PHP: Step-by-Step Tutorial with Graph SDK

Table Of Content

1 Prerequisites

  • PHP 8.0+ (recommended; works with 7.4+)
  • Composer installed
  • Local server (e.g., XAMPP, Laravel Valet, or PHP built-in server)

2 Introduction

Add seamless Facebook Login to your PHP application using OAuth 2.0 and the official Facebook Graph SDK. This allows users to sign in with their Facebook account, eliminating password creation and improving UX/conversion rates.

This guide uses Composer for installation and assumes a basic PHP setup. Updated for current Graph API versions (use the latest default, typically v19.0–v22.0 as of 2026).

3 Create Project Folder "facebook-login-app"

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

4 Install Facebook Graph 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 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.

// config.php
define('FACEBOOK_APP_ID', 'your-app-id-here');
define('FACEBOOK_APP_SECRET', 'your-app-secret-here');
define('FACEBOOK_REDIRECT_URI', 'http://localhost:8000/facebook-callback.php');
define('FACEBOOK_GRAPH_VERSION', 'v19.0'); // Use latest stable version 

7 Create the Login Page (index.php or login.php)

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

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

$fb = new \Facebook\Facebook([
    'app_id' => FACEBOOK_APP_ID,
    'app_secret' => FACEBOOK_APP_SECRET,
    'default_graph_version' => FACEBOOK_GRAPH_VERSION,
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email']; // Add more if needed: public_profile, etc.
$loginUrl = $helper->getLoginUrl(FACEBOOK_REDIRECT_URI, $permissions);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login with Facebook - PHP Tutorial</title>
</head>
<body>
    <h1>Sign In</h1>
    <a href="<?php echo htmlspecialchars($loginUrl); ?>">Login with Facebook</a>
</body>
</html>

8 Handle the Facebook Callback (facebook-callback.php)

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

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

$fb = new \Facebook\Facebook([...]); // same as above

$helper = $fb->getRedirectLoginHelper();

try {
    $accessToken = $helper->getAccessToken();
} 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;
}

if (! isset($accessToken)) {
    echo 'No access token received.';
    exit;
}

// Optional: Exchange for long-lived token
// $client = $fb->getOAuth2Client();
// $longLivedToken = $client->getLongLivedAccessToken($accessToken);

$_SESSION['fb_access_token'] = (string) $accessToken;

// Get user data
try {
    $response = $fb->get('/me?fields=id,name,email', $accessToken);
    $user = $response->getGraphUser();
    $_SESSION['fb_user'] = [
        'id' => $user['id'],
        'name' => $user['name'],
        'email' => $user['email'] ?? 'Not provided',
    ];
} catch (\Exception $e) {
    echo 'Error fetching user: ' . $e->getMessage();
    exit;
}

header('Location: dashboard.php');
exit;

9 Build a Protected Dashboard (dashboard.php)

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

<?php
session_start();
if (!isset($_SESSION['fb_user'])) {
    header('Location: index.php');
    exit;
}
$user = $_SESSION['fb_user'];
?>

<!DOCTYPE html>
<html lang="en">
<head><title>Dashboard</title></head>
<body>
    <h1>Welcome, <?php echo htmlspecialchars($user['name']); ?>!</h1>
    <p>Email: <?php echo htmlspecialchars($user['email']); ?></p>
    <p>Facebook ID: <?php echo htmlspecialchars($user['id']); ?></p>
    <a href="logout.php">Logout</a>
</body>
</html>

10 Add Logout Functionality (logout.php)

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

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

11 Folder Structure

12 How to Run & Test

  • Replace YOUR_APP_ID_HERE and YOUR_APP_SECRET_HERE in config.php
  • In Meta for Developers → Your App → Facebook Login → Settings:
  • Add Valid OAuth Redirect URIs: http://localhost:8000/facebook-callback.php (exact match!)
  • Start PHP server in the project folder:hphp -S localhost:8000
  • Visit http://localhost:8000/login.php
  • Click "Login with Facebook" → Authorize → See dashboard

13 Conclusion

You've now implemented Facebook Login in PHP successfully! This flow is secure, scalable, and uses the official SDK. For frameworks like Laravel, consider socialite packages instead.
Revathi M - PHP and CodeIgniter Developer

Written by Revathi M

PHP Developer & Technical Writer · 10+ years building web applications with CodeIgniter and Laravel

Revathi specializes in PHP backend development, authentication systems, and REST API design. She writes practical, production-tested tutorials at Get Sample Code to help developers build secure applications faster.

Frequently Asked Questions

You need PHP 7.4 or higher, along with Composer installed.

Run the command: composer require facebook/graph-sdk. This installs the official Facebook Graph SDK.

Go to developers.facebook.com, create a new app, select 'Authenticate and request data from users with Facebook Login', add your site URL as a platform, and note the App ID and App Secret.

The tutorial requests the 'email' permission by default. You can add more to the $permissions array.

Use $helper = $fb->getRedirectLoginHelper(); then $loginUrl = $helper->getLoginUrl(FACEBOOK_REDIRECT_URI, $permissions); and link to it.

In facebook-callback.php, use $helper->getAccessToken() to retrieve the token, exchange for a long-lived token if needed, validate it, and store in session.

The tutorial fetches id, name, and email via /me?fields=id,name,email Graph API endpoint and stores them in session.

No, user data is stored only in PHP sessions ($_SESSION). No database is required.

The redirect URI in config.php must exactly match the one added in Facebook App settings under OAuth Redirect URIs. Use the full URL like http://localhost/your-folder/facebook-callback.php.

Create a logout.php file that calls session_destroy() and redirects back to login.php.