Implement Facebook Login in PHP

by Lovepreet 3 minute read 27 views

Over 2.9 billion monthly users rely on Facebook. Integrating Facebook login in PHP enables faster authentication, secure access, and improved user engagement for web apps.

Key Points

  • 70% of users prefer social logins like Facebook over creating new accounts manually.
  • Websites with Facebook login experience 50% more sign-ups than traditional registration methods.
  • Using Facebook SDK cuts development time by 40% when adding login to PHP apps.

Integrating Facebook Login into your website allows users to quickly access your platform without creating a new account. It enhances user experience, improves engagement, and builds trust. In this guide, we’ll walk you through how to implement Facebook login in PHP step by step.

If you’re working on custom web development or planning a scalable solution, Facebook login integration can be a great addition.

Why Use Facebook Login in PHP?

  • Quick Authentication – Users can log in with their existing Facebook accounts.
  • Increased Engagement – Eliminates signup friction.
  • Secure and Reliable – Facebook handles password management.
  • Customizable – You can fetch profile details, emails, and more to personalize user experience.

If you don’t have technical expertise, you can always hire PHP developer experts to implement this securely and efficiently.

Step 1: Install Facebook PHP SDK

To begin, install the Facebook SDK for PHP. If you are using Composer, run:

                                        composer require facebook/graph-sdk
                                    

This SDK offers all the essential tools to integrate OAuth authentication with Facebook, making it a reliable choice for custom website development projects.

Step 2: Create and Configure Facebook App

To authenticate via Facebook, you need to create a Facebook App:

  1. Go to Facebook Developers.
  2. Create an account (if you don’t have one) and then create a new app.
  3. Enable Facebook Login.
  4. Note down the App ID and App Secret.
  5. Set a Valid OAuth Redirect URI (e.g., http://localhost/fb-callback.php).

You’ll use these credentials in your PHP application.

Step 3: Add Facebook Credentials in PHP

Create a configuration file (config.php) and add the following:

                                        <?php
require_once __DIR__ . '/vendor/autoload.php';

$fb = new \Facebook\Facebook([
  'app_id' => 'YOUR_FACEBOOK_APP_ID',
  'app_secret' => 'YOUR_FACEBOOK_APP_SECRET',
  'default_graph_version' => 'v17.0',
]);

$callbackUrl = 'http://localhost/fb-callback.php'; // Change for production
$helper = $fb->getRedirectLoginHelper();

$permissions = ['email']; // Permissions you want
$loginUrl = $helper->getLoginUrl($callbackUrl, $permissions);
?>
                                    

Step 4: Create Login Page

Add a "Login with Facebook" button in your login.php file:

                                        <?php include 'config.php'; ?>
<!DOCTYPE html>
<html>
<head>
    <title>Facebook Login in PHP</title>
</head>
<body>
    <a href="<?php echo htmlspecialchars($loginUrl); ?>" 
       style="background:#1877f2;color:white;padding:10px 15px;text-decoration:none;border-radius:5px;">
       <i class="fa fa-facebook-square"></i> Login with Facebook
    </a>
</body>
</html>
                                    

This will redirect users to Facebook for authentication.

Step 5: Handle Facebook Callback

Create a file called fb-callback.php to process the response from Facebook:

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

$fb = new \Facebook\Facebook([
  'app_id' => 'YOUR_FACEBOOK_APP_ID',
  'app_secret' => 'YOUR_FACEBOOK_APP_SECRET',
  'default_graph_version' => 'v17.0',
]);

$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 'Unable to get access token.';
  exit;
}

// Save access token
$_SESSION['facebook_access_token'] = (string) $accessToken;

// Fetch user profile data
try {
  $response = $fb->get('/me?fields=id,name,email', $accessToken);
  $user = $response->getGraphUser();

  echo "Name: " . $user['name'] . "<br>";
  echo "Email: " . $user['email'] . "<br>";
  echo "Facebook ID: " . $user['id'];

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

Step 6: Store User Data in Database

If you want to store the user data, you can save it in your database. Example with MySQL:

                                        $conn = new mysqli("localhost", "root", "", "testdb");

$name = $user['name'];
$email = $user['email'];
$facebook_id = $user['id'];

$sql = "INSERT INTO users (name, email, facebook_id) 
        VALUES ('$name', '$email', '$facebook_id')
        ON DUPLICATE KEY UPDATE name='$name'";

$conn->query($sql);
                                    

This guarantees that users are either created or updated upon logging in with Facebook.

Best Practices

  • Always use HTTPS for security.
  • Store access tokens securely in your database.
  • Implement a proper logout system.
  • Use Facebook’s API limits wisely.

If you’re working on custom web development, adding features like social login, payment gateways, and custom dashboards can greatly enhance your application.

For businesses lacking in-house expertise, it’s advised to hire PHP developer professionals who can deliver secure, optimized, and scalable integration.

Final Words

Implementing Facebook Login in PHP is straightforward with the Facebook SDK. It enhances user experience, boosts signups, and ensures security. Whether you’re building a small project or a large-scale custom web development platform, integrating Facebook login can make your application more user-friendly.

If you don’t want to handle the technical complexities yourself, you can always hire PHP developer experts to implement and customize it according to your business needs.

Tech Stack & Version

Frontend

  • HTML
  • CSS
  • JS

 

Backend

  • PHP
  • MySQL

Deployment

  • AWS
  • DigitalOcean
img

©2025Digittrix Infotech Private Limited , All rights reserved.