JQuery Facebook Login with PHP & MySQL.

JQuery Facebook Login with PHP & MySQL.

Aug 1, 2018 | MySql, PHP

Quickstart With Facebook the JavaScript SDK

http://developers.facebook.com/apps/

Later in this doc we will guide you through the login flow step-by-step and explain each step clearly – this will help you if you are trying to integrate Facebook Login into an existing login system, or just to integrate it with any server-side code you’re running. But before we do that, it’s worth showing how little code is required to implement login in a web application using the JavaScript SDK.
You will need a Facebook App ID before you start using the SDK, which you can create and retrieve on the App Dashboard. You’ll also need somewhere to host HTML files.
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
  // This is called with the results from from FB.getLoginStatus().
  function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
      // Logged into your app and Facebook.
      testAPI();
    } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
    } else {
      // The person is not logged into Facebook, so we're not sure if
      // they are logged into this app or not.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into Facebook.';
    }
  }

  // This function is called when someone finishes with the Login
  // Button.  See the onlogin handler attached to it in the sample
  // code below.
  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
  FB.init({
    appId      : '{your-app-id}',
    cookie     : true,  // enable cookies to allow the server to access 
                        // the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.2' // use version 2.2
  });

  // Now that we've initialized the JavaScript SDK, we call 
  // FB.getLoginStatus().  This function gets the state of the
  // person visiting this page and can return one of three states to
  // the callback you provide.  They can be:
  //
  // 1. Logged into your app ('connected')
  // 2. Logged into Facebook, but not your app ('not_authorized')
  // 3. Not logged into Facebook and can't tell if they are logged into
  //    your app or not.
  //
  // These three cases are handled in the callback function.

  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });

  };
  // Load the SDK asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

  // Here we run a very simple test of the Graph API after login is
  // successful.  See statusChangeCallback() for when this call is made.


  function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';
    });
  }
</script>

<!--
  Below we include the Login Button social plugin. This button uses
  the JavaScript SDK to present a graphical Login button that triggers
  the FB.login() function when clicked.
-->

<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
</body>
</html>

This code will load and initialize the JavaScript SDK in your HTML page. Use your app ID where indicated.

Now you can test your app by going to the URL where you uploaded this HTML. Open your JavaScript console, and you’ll see the testAPI() function display a message with your name in the console log.

Congratulations, at this stage you’ve actually built a really basic page with Facebook Login. You can use this as the starting point for your own app, but it will be useful to read on and understand what is happening in the code above.

Create User Table

Run MySql query below in phpMyAdmin to create a table called “usertable“, table contains 4 fields. id(Int, Auto Increment), fbid (BigInt, Facebook ID), fullname(Varchar, Full Name),profi;e_photo(Varchar, Profile Large Picture) and email(Varchar, Email).

 

CREATE TABLE IF NOT EXISTS `usertable` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `fbid` bigint(20) NOT NULL,
  `fullname` varchar(60) NOT NULL,
  `email` varchar(60) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;?

Configuration File

Create Facebook application and replace values in config.php file. Specify return URL and permissions required by your application.

########## app ID and app SECRET (Replace with yours) #############
$appId = 'xxxxxx'; //Facebook App ID
$appSecret = 'xxxxxxxxxxxxxx'; // Facebook App Secret
$return_url = 'http://yoursite.com/connect_script/';  //path to script folder
$fbPermissions = 'publish_actions,email'; //more permissions : https://developers.facebook.com/docs/authentication/permissions/

########## MySql details (Replace with yours) #############
$db_username = "xxxxxx"; //Database Username
$db_password = "xxxxxx"; //Database Password
$hostname = "localhost"; //Mysql Hostname
$db_name = 'database_name'; //Database Name
###################################################################

Login Button

I have attached javascript SDK in the page that comes with their login button plugin, but login button is not official, it was later created by myself using CSS and image because the error “FB.login called when user is already logged in” keeps appearing with official button when attaching CallAfterLogin() function to its onlogin attribute.
<a href="#" rel="nofollow" class="fblogin-button" onClick="javascript:CallAfterLogin();return false;">Login with Facebook</a>
You can render their official button if you want, just by placing their HTML block once their JavaScript SDK is loaded in the page, just remember to add onlogin and scope attributes, onlogin attribute is required to attach our CallAfterLogin() function:

 

<div class="fb-login-button" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="false" onlogin="javascript:CallAfterLogin();" scope="publish_actions,email"></div>
To check whether user is logged in or not in this tutorial, I’ve created session variable called $_SESSION[‘logged_in’], if you are using some user management system in your website, you have to make appropriate changes here.
session_start();
include_once("include/config.php");

if(!isset($_SESSION['logged_in']))
{
    echo '<div id="results">';
    echo '<!-- results will be placed here -->';
    echo '</div>';
    echo '<div id="LoginButton">';
    echo '<a href="javascript:void(0)" rel="nofollow" class="fblogin-button" onClick="javascript:CallAfterLogin();return false;">Login with Facebook</a>';
    echo '</div>';

}
else
{
    echo 'Hi '. $_SESSION['user_name'].'! You are Logged in to facebook, <a href="?logout=1">Log Out</a>.';
}

Here’s the javascript code.

<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
    FB.init({
        appId: '<?php echo $appId; ?>',
        cookie: true,xfbml: true,
        channelUrl: '<?php echo $return_url; ?>channel.php',
        oauth: true
        });
    };
(function() {
    var e = document.createElement('script');
    e.async = true;e.src = document.location.protocol +'//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);}());

function CallAfterLogin(){
    FB.login(function(response) {      
        if (response.status === "connected")
        {
            LodingAnimate(); //Animate login
            FB.api('/me', function(data) {
               
              if(data.email == null)
              {
                    //Facbeook user email is empty, you can check something like this.
                    alert("You must allow us to access your email id!");
                    ResetAnimate();

              }else{
                    AjaxResponse();
              }
             
          });
         }
    },
    {scope:'<?php echo $fbPermissions; ?>'});
}

//functions
function AjaxResponse()
{
     //Load data from the server and place the returned HTML into the matched element using jQuery Load().
     $( "#results" ).load( "process_facebook.php" );
}

//Show loading Image
function LodingAnimate()
{
    $("#LoginButton").hide(); //hide login button once user authorize the application
    $("#results").html('<img src="img/ajax-loader.gif" /> Please Wait Connecting...'); //show loading image while we process user
}

//Reset User button
function ResetAnimate()
{
    $("#LoginButton").show(); //Show login button
    $("#results").html(''); //reset element html
}
</script>

Process Requests

Once the Ajax request is made to process_facebook.php, it connects to Facebook and retrieves user details, and stores them in database table. Since we already have user session with JavaScript SDK, PHP-SDK should have no trouble using the Facebook session and APIs.
session_start();
include_once("include/config.php"); //Include configuration file.
require_once('include/facebook.php' ); //include fb sdk

/* Detect HTTP_X_REQUESTED_WITH header sent by all recent browsers that support AJAX requests. */
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{      

    //initialize facebook sdk
    $facebook = new Facebook(array(
        'appId' => $appId,
        'secret' => $appSecret,
    ));
   
    $fbuser = $facebook->getUser();
   
    if ($fbuser) {
        try {
            // Proceed knowing you have a logged in user who's authenticated.
            $me = $facebook->api('/me'); //user
            $uid = $facebook->getUser();
        }
        catch (FacebookApiException $e)
        {
            //echo error_log($e);
            $fbuser = null;
        }
    }
   
    // redirect user to facebook login page if empty data or fresh login requires
    if (!$fbuser){
        $loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$return_url, false));
        header('Location: '.$loginUrl);
    }
   
    //user details
    $fullname = $me['first_name'].' '.$me['last_name'];
    $email = $me['email'];

    /* connect to mysql using mysqli */
   
    $mysqli = new mysqli($hostname, $db_username, $db_password,$db_name);
    if ($mysqli->connect_error) {
        die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
    }
   
    //Check user id in our database
    $UserCount = $mysqli->query("SELECT COUNT(id) as usercount FROM usertable WHERE fbid=$uid")->fetch_object()->usercount;
   
    if($UserCount)
    {  
        //User exist, Show welcome back message
        echo 'Ajax Response :<br /><strong>Welcome back '. $me['first_name'] . ' '. $me['last_name'].'!</strong> ( Facebook ID : '.$uid.') [<a href="'.$return_url.'?logout=1">Log Out</a>]';
       
        //print user facebook data
        echo '<pre>';
        print_r($me);
        echo '</pre>';

        //User is now connected, log him in
        login_user(true,$me['first_name'].' '.$me['last_name']);
    }
    else
    {
        //User is new, Show connected message and store info in our Database
        echo 'Ajax Response :<br />Hi '. $me['first_name'] . ' '. $me['last_name'].' ('.$uid.')! <br /> Now that you are logged in to Facebook using jQuery Ajax [<a href="'.$return_url.'?logout=1">Log Out</a>].
        <br />the information can be stored in database <br />';
        //print user facebook data
        echo '<pre>';
        print_r($me);
        echo '</pre>';
       
        // Insert user into Database.
        $mysqli->query("INSERT INTO usertable (fbid, fullname, email) VALUES ($uid, '$fullname','$email')");
               
    }
   
    $mysqli->close();
}

function login_user($loggedin,$user_name)
{
    /*
    function stores some session variables to imitate user login.
    We will use these session variables to keep user logged in, until s/he clicks log-out link.
    */
    $_SESSION['logged_in']=$loggedin;
    $_SESSION['user_name']=$user_name;
}

That’s it! I am sure this will help you make your own Ajax Facebook Login with PHP SDK version 4 with significant changes, Good luck.

Being Idea is a web platform of programming tutorials to make better programming skills and provides Software Development Solutions.

0 Comments

Leave a Reply