Login with Facebook using JavaScript SDK Tutorial

Introduction

In this tutorial, you will learn how to Implement a Login with Facebook Feature in your web applications using Facebook SDK for JavaScript. The tutorial aims to provide a reference for IT/CS students and new programmers for learning and implementing a web OAuth Login using Facebook. Here, snippets are provided and a sample source code file is provided and free to download.

Getting Started

In this tutorial, we will use XAMPP software to run an Apache Server on our local machine. The interface snippets use CDNs for loading the external libraries (Bootstrap and jQUery) on the application. Please make sure to be connected to the internet in order to run the snippets properly.

Before we start on the coding part, we will create an Application on Facebook First. To do that, kindly follow the instructions below.

Creating a Facebook

  • Open your preferred browser and browse the Facebook Developers Apps Page
  • Next, click the "Create App" button

    Meta for Developers - Create App Step 1

  • Since this is just a test, select "None" as the App's Type Options.

    Meta for Developers - Create App Step 2

  • Next, fill in the required inputs on the basic information about your App.

    Meta for Developers - Create App Step 3

  • After your App has been successfully created, click the "Set up" button of the Facebook Login Product on the dashboard page.

    Meta for Developers - Create App Step 4

  • Next, select the "WWW" option.

    Meta for Developers - Create App Step 5

  • Next, enter your site's URL and save it.

    Meta for Developers - Create App Step 6

  • Then, on the page sidebar, you can see the "Facebook Login" dropdown menu and select settings. After the page redirects to the settings page, toggle the "Login with JavaScript SDK" to yes and enter your site's domain. Save the settings.

    Meta for Developers - Create App Step 7

Creating the Authentication Checker

After creating an App on Facebook for Developers, let's create the Authentication Checker File of the sample page. On your source code folder in htdocs, create a new PHP file and save it as auth.php

  1.     <?php
  2.     session_start();
  3.    
  4.     if(!isset($_SESSION['fb_id']) || (isset($_SESSION['fb_id']) && empty($_SESSION['fb_id']))){
  5.         if(strstr($_SERVER['PHP_SELF'], 'login.php') === false)
  6.         header('location:login.php');
  7.     }else{
  8.         if(strstr($_SERVER['PHP_SELF'], 'index.php') === false)
  9.         header('location:index.php');
  10.     }
  11.    

Creating the Login Page Interface

Next, create a new PHP file and save it as index.php

  1.     <?php require_once('auth.php') ?>
  2.     <?php
  3.    if(isset($_GET['logout'])){
  4.        session_destroy();
  5.        header('location: login.php');
  6.    }
  7.    ?>
  8.     <!DOCTYPE html>
  9.     <html lang="en">
  10.     <head>
  11.         <meta charset="UTF-8">
  12.         <meta http-equiv="X-UA-Compatible" content="IE=edge">
  13.         <meta name="viewport" content="width=device-width, initial-scale=1.0">
  14.         <title>Home | FB Login using JS SDK</title>
  15.         <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  16.         <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  17.         <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  18.    
  19.     </head>
  20.     <body>
  21.         <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  22.             <div class="container">
  23.                 <a class="navbar-brand" href="./">Sample Site</a>
  24.                 <div>
  25.                     <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  26.                 </div>
  27.             </div>
  28.         </nav>
  29.         <div class="container my-5">
  30.             <div class="row">
  31.                 <div class="col-lg-5 col-md-7 col-sm-12 mx-auto">
  32.                     <div class="card rounded-0">
  33.                         <div class="card-body">
  34.                             <div class="container-fluid">
  35.                                 <h2>You are Logged In</h2>
  36.                                 <hr>
  37.                                 <div class="text-center">
  38.                                     <img src="<?= $_SESSION['fb_profile_pic'] ?>" alt="" class="img-thumb-nail rounded-circle">
  39.                                 </div>
  40.                                 <dl>
  41.                                     <dt>Name</dt>
  42.                                     <dd class="ps-4"><?= ucwords($_SESSION['fb_name']) ?></dd>
  43.                                     <dt>Email</dt>
  44.                                     <dd class="ps-4"><?= $_SESSION['fb_email']  ?></dd>
  45.                                     <dt>Gender</dt>
  46.                                     <dd class="ps-4"><?= ucwords($_SESSION['fb_gender'])  ?></dd>
  47.                                 </dl>
  48.                                 <hr>
  49.                                 <div class="text-center">
  50.                                     <a href="logout.php" id="logout_btn" class="btn btn btn-danger btn-sm rounded-0">Logout</a>
  51.                                 </div>
  52.                             </div>
  53.                         </div>
  54.                     </div>
  55.                 </div>
  56.             </div>
  57.         </div>
  58.     </body>
  59.    
  60.     <script src="./fb-login/fb-login.js"></script>
  61.    
  62.     </html>

Creating the Sign-in Script

Next, let's create the PHP Script that saves the logged-in user data on the session. Save the file as sign-in.php

  1. <?php
  2. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  3.     foreach($_POST as $k => $v){
  4.         if($k=='picture')
  5.         $_SESSION['fb_profile_pic'] = $v['data']['url'];
  6.         else
  7.         $_SESSION['fb_'.$k] = $v;
  8.     }    
  9.     echo json_encode(['status' => 'success']);
  10. }else{
  11.     echo json_encode(['status' => 'failed']);
  12. }
  13. ?>

Creating the Home Page Interface

The snippet below is the script that contains the HTML elements and PHP Scripts for displaying the data of the logged-in user using Facebook. Save the file as index.php.

  1.     <?php require_once('auth.php') ?>
  2.     <?php
  3.    if(isset($_GET['logout'])){
  4.        session_destroy();
  5.        header('location: login.php');
  6.    }
  7.    ?>
  8.     <!DOCTYPE html>
  9.     <html lang="en">
  10.     <head>
  11.         <meta charset="UTF-8">
  12.         <meta http-equiv="X-UA-Compatible" content="IE=edge">
  13.         <meta name="viewport" content="width=device-width, initial-scale=1.0">
  14.         <title>Home | FB Login using JS SDK</title>
  15.         <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  16.         <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  17.         <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  18.    
  19.     </head>
  20.     <body>
  21.         <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  22.             <div class="container">
  23.                 <a class="navbar-brand" href="./">Sample Site</a>
  24.                 <div>
  25.                     <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  26.                 </div>
  27.             </div>
  28.         </nav>
  29.         <div class="container my-5">
  30.             <div class="row">
  31.                 <div class="col-lg-5 col-md-7 col-sm-12 mx-auto">
  32.                     <div class="card rounded-0">
  33.                         <div class="card-body">
  34.                             <div class="container-fluid">
  35.                                 <h2>You are Logged In</h2>
  36.                                 <hr>
  37.                                 <div class="text-center">
  38.                                     <img src="<?= $_SESSION['fb_profile_pic'] ?>" alt="" class="img-thumb-nail rounded-circle">
  39.                                 </div>
  40.                                 <dl>
  41.                                     <dt>Name</dt>
  42.                                     <dd class="ps-4"><?= ucwords($_SESSION['fb_name']) ?></dd>
  43.                                     <dt>Email</dt>
  44.                                     <dd class="ps-4"><?= $_SESSION['fb_email']  ?></dd>
  45.                                     <dt>Gender</dt>
  46.                                     <dd class="ps-4"><?= ucwords($_SESSION['fb_gender'])  ?></dd>
  47.                                 </dl>
  48.                                 <hr>
  49.                                 <div class="text-center">
  50.                                     <a href="logout.php" id="logout_btn" class="btn btn btn-danger btn-sm rounded-0">Logout</a>
  51.                                 </div>
  52.                             </div>
  53.                         </div>
  54.                     </div>
  55.                 </div>
  56.             </div>
  57.         </div>
  58.     </body>
  59.    
  60.     <script src="./fb-login/fb-login.js"></script>
  61.    
  62.     </html>

Creating the Logout Script

Next, create the PHP Script that destroys the session data upon logging out. Save the snippet below as logout.php.

  1. <?php
  2. foreach($_SESSION as $k => $v){
  3.     unset($_SESSION[$k]);
  4. }
  5. header('location: login.php');

Creating the JavaScript

Lastly, let's create the JavaScript codes that initiate the Facebook login button, login event listener, and logout event listener, and include the Facebook SDK for JavaScript. In my case, I save this file inside the fb-login directory and named the file as fb-login.php. This file is loaded both in index.php and login.php.

  1. var logout_btn = document.getElementById('logout_btn')
  2.  
  3. window.fbAsyncInit = function() {
  4.     FB.init({
  5.     appId      : '{app-ID}', // Change this with your Created App ID
  6.     cookie     : true,
  7.     xfbml      : true,
  8.     version    : 'v2.7'
  9.     });
  10.    
  11.     FB.AppEvents.logPageView();  
  12.    
  13.     /**
  14.     * Check Login Status
  15.     */
  16.     FB.getLoginStatus(function(response) {
  17.     fbStatusChange(response);
  18.     });
  19.  
  20.    
  21. };
  22.  
  23. (function(d, s, id){
  24.     var js, fjs = d.getElementsByTagName(s)[0];
  25.     if (d.getElementById(id)) {return;}
  26.     js = d.createElement(s); js.id = id;
  27.     js.src = "https://connect.facebook.net/en_US/sdk.js";
  28.     fjs.parentNode.insertBefore(js, fjs);
  29.     }(document, 'script', 'facebook-jssdk'));
  30.  
  31.  
  32. /**
  33.     * After Login
  34.     */
  35.     function fbLogin(){
  36.     FB.login(function(response){
  37.     fbStatusChange(response)
  38.     })
  39.     }
  40.  
  41.     /**
  42.     * Save FB User Data to Session
  43.     */
  44.     function fbStatusChange(loginResp){
  45.     console.log(loginResp)
  46.     if(loginResp.status =='connected' && (location.origin + location.pathname) == 'https://localhost/js-fb-login/login.php'){
  47.     FB.api('/me', 'GET', {fields: 'email,name,gender,picture{url}' }, function(response) {
  48.         if(!response.error){
  49.         $.ajax({
  50.             url:'sign-in.php',
  51.             method:"POST",
  52.             data: response,
  53.             dataType:"JSON",
  54.             error:function(err){
  55.                 alert("Login Failed!")
  56.                 console.error(err)
  57.             },
  58.             success:function(resp){
  59.             if(resp.status == 'success'){
  60.                 location.replace('index.php');
  61.             }else{
  62.                 alert("Login Failed!")
  63.             }
  64.             }
  65.    
  66.         })
  67.         }else{
  68.             alert("Login Failed!")
  69.             console.error(response.error)
  70.         }
  71.        
  72.     });
  73.     }
  74.     }
  75.  
  76.  
  77.     /**
  78.     * Logout Facebook
  79.     */
  80. if(logout_btn !== undefined && logout_btn !== null){
  81.     logout_btn.addEventListener('click', function(e){
  82.     e.preventDefault()
  83.     FB.logout(function(){
  84.         console.log('Facebook Account has been logged out to this application.')
  85.     })
  86.     location.replace(this.getAttribute('href'))
  87.     })
  88. }

That's it! You can now test the source code that we created and see if works as we plan.

Application Snapshots

Here are some snapshots of the application.

Login Button

Login with Facebook App

Home Page

Login with Facebook App

That's the end of this tutorial. I have also provided the source code file that I created for this tutorial. you can download it by clicking the Download button located after this article. I hope this Login with Facebook using JavaScript SDK Tutorial helps you with what you are looking for and that you'll find this useful for your current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment