Login with Facebook using JavaScript and PHP

Do you want to add a Facebook login option to your website? Nowadays users prefer to sign in through social sites instead of following the lengthy registration process. The user doesn’t want to remember their credentials for your website. They simply use the social site’s login and get entered into the website. Social sites like Facebook, Google, Twitter, etc provide the SDK that can be used to integrate their login flow.

In this article, I show you adding login with Facebook using JavaScript and PHP. The JavaScript SDK allows you to add a Facebook login popup at the click of a button. On the server-side, we will use PHP and MySQL to store the user information and log the user into the website. I’ll use PHP and JavaScript SDK to logout the user out of the website and Facebook.

Create the Facebook App

To integrate Facebook login into the website you require to create an App on your Facebook Developer account. Here are the instructions to follow.

  • While logged into your Facebook account, go to the Facebook for Developers website and click Get Started.
  • Go to the Apps and click Create App.
  • Choose an App type.
  • Enter the name of your app and email address.
  • From the listed Products, choose Facebook Login.
  • You need to provide an App domain(website URL) which must be served on https.
  • On Facebook Login -> Settings page, enable Login with the JavaScript SDK.
  • On the same page, add your domain URL under Allowed Domains for the JavaScript SDK. Refer to the screenshot below.
facebook-allowed-domain

Copy your App ID, it will be required in the next steps. If you find difficulties in creating a Facebook App then you can refer to the official documentation.

Database Configuration

Every login/registration system requires storing user details in the database. Create the users table using the below SQL.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `fb_uid` varchar(255) NOT NULL,
 `name` varchar(255) NOT NULL,
 `email` varchar(255) NOT NULL
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

We’ll be required to run a few database queries. Let’s write some methods for it. Create a class-db.php and write database connection, the functions to fetch and insert/update the users.

In the users table, I keep the fb_uid column to hold the unique id of a Facebook user. Through this id, we check if the user already exists and accordingly either insert or update details in the database.

class-db.php

<?php
class DB {
    private $dbHost     = "DB_HOST";
    private $dbUsername = "DB_USERNAME";
    private $dbPassword = "DB_PASSWORD";
    private $dbName     = "DB_NAME";
 
    public function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
 
    public function get_user($id) {
        $sql = $this->db->query("SELECT * FROM users WHERE fb_uid = '$id'");
        return $sql->fetch_assoc();
    }
 
    public function upsert_user($arr_data = array()) {
        $uid = $arr_data['id'];
        $name = $arr_data['name'];
        $email = $arr_data['email'];
 
        // check if user exists by fetching it's details
        $user = $this->get_user($uid);
 
        if(!$user) {
            // insert the user
            $this->db->query("INSERT INTO users(fb_uid, name, email) VALUES('$uid', '$name', '$email')");
        } else {
            // update the user
            $this->db->query("UPDATE users SET name = '$name', email = '$email' WHERE fb_uid = '$uid'");
        }
    }
}

Facebook Login using JavaScript SDK

Facebook provides ready-to-use code that initializes JavaScript SDK in your HTML pages. I am creating a login.php file and adding code for JavaScript SDK into it. Along with this, I’ll handle the following scenarios in the same file.

  • Using a PHP session, I’ll check if the user is already logged in to the system. If yes, then redirect them to the profile.php URL.
  • Send the user details received from Facebook to the server-side script called save-user.php. This file will be responsible for setting the user’s session and storing their information.

login.php

<?php
session_start();

// logged in user shouldn't access this page
if(isset($_SESSION['uid'])) {
    header('Location: profile.php');
}
?>

<script>
function statusChangeCallback(response) {  // Called with the results from FB.getLoginStatus().
    if (response.status === 'connected') { // Logged into your webpage and Facebook.
        saveUserData();  
    }
}

function checkLoginState() {               // Called when a person is finished with the Login Button.
    FB.getLoginStatus(function(response) { // See the onlogin handler
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function() {
    FB.init({
    appId      : '{app-id}',
    cookie     : true,                     // Enable cookies to allow the server to access the session.
    xfbml      : true,                     // Parse social plugins on this webpage.
    version    : 'v13.0'                   // Use this Graph API version for this call.
    });

    FB.getLoginStatus(function(response) {   // Called after the JS SDK has been initialized.
        statusChangeCallback(response);      // Returns the login status.
    });
};

function saveUserData() {                      // Testing Graph API after login.  See statusChangeCallback() for when this call is made.
    FB.api('/me', { fields: 'id, name, email' }, function(response) {
        // send ajax request
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                if('success' == this.responseText) {
                    // redirect to profile page
                    location.href = 'DOMAIN_URL/profile.php';
                }
            }
        };
        xhttp.open("POST", "save-user.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("response=" + JSON.stringify(response));
    });
}
</script>


<!-- The JS SDK Login Button -->
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();"></fb:login-button>

<div id="status"></div>

<!-- Load the JS SDK asynchronously -->
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>

Make sure to replace the placeholder {app-id} with its actual value. Also, I passed the version as v13.0 which is the latest one. You may find the latest version number under the Settings->Advanced->API Version.

facebook-api-version

Upon receiving a successful response from the server-side script, I am redirecting a user to the profile.php URL.

Save User Information

We have given a call to save.user.php after the user signs in to Facebook. In this file, we write a code to store the user’s information. I also set the user in the PHP session variable. Through this session, the application keeps the user logged in.

<?php
session_start();
require_once 'class-db.php';
 
$arr_user_data = json_decode($_POST['response'], true);

if (!empty($arr_user_data)) {
    $db = new DB();
 
    // send user data to the database
    $db->upsert_user($arr_user_data);
 
    // set user id in session aka log in the user
    if(!isset($_SESSION['uid'])) {
        $_SESSION['uid'] = $arr_user_data['id'];
    }
 
    echo 'success';
} else {
    echo 'Invalid Token';
}

profile.php and Log out User

After successful login with Facebook, the user comes to the profile.php URL. The profile.php URL should not be accessible to non-logged-in users. I’ll handle this situation using the PHP session. Upon successful login, we already set the user in session. If the session variable is null on this profile.php page, we redirect the user to the login page.

Let’s add the code for logout in the same file. When a user hits the logout link, they will log out from your application and from Facebook.

<?php
session_start();

// non-logged in user shouldn't access this page
if(!isset($_SESSION['uid'])) {
    header('Location: login.php');
}

// log out the user and redirect to login page
if(isset($_GET['action']) && ('logout' == $_GET['action'])) {
    unset($_SESSION['uid']);
    header('Location: login.php');
}

require_once 'class-db.php';
$db = new DB();
$user = $db->get_user($_SESSION['uid']);

echo "Welcome ". $user['name'];
?>

<script>
function fbLogout() {
    FB.getLoginStatus(function(response) {   // Called after the JS SDK has been initialized.
        if (response.status === 'connected') {   // Logged into your webpage and Facebook.
            console.log('Log out the user');
            FB.logout(function(response) {
                console.log('Person is now logged out');
            });
        }
    });

    return true;
}

window.fbAsyncInit = function() {
    FB.init({
    appId      : '{app-id}',
    cookie     : true,                     // Enable cookies to allow the server to access the session.
    xfbml      : true,                     // Parse social plugins on this webpage.
    version    : 'v13.0'           // Use this Graph API version for this call.
    });
};
</script>

<p><a href='profile.php?action=logout' onclick="return fbLogout();">Log out</a></p>

<!-- Load the JS SDK asynchronously -->
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>

You are now ready to test the flow. Run the login.php URL on the browser. On clicking the login button, a Facebook login popup will open. Add your Facebook credentials. You will redirect to the profile.php URL and the details should be stored in the database.

Click on the logout link and you will find yourselves logging out of your application and from Facebook.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

1 thought on “Login with Facebook using JavaScript and PHP

  1. Facebook want me to verify and validate my business using this. Is this requiered now? it wasent in the past.

    Thanks in advance.

Leave a Reply

Your email address will not be published. Required fields are marked *