Saturday, April 14, 2018

“Log In With Facebook” for Website using PHP

(1) Download the zipped form of Facebook SDK for PHP from the following link: https://github.com/facebook/php-graph-sdk
(2) Unzip it and find Facebook folder inside the php-graph-sdk/src folder. Next put the Facebook folder inside your project directory (say in your http://localhost/FacebookLogin/ folder).
(3) Now, we create a file (say config.php) in FacebookLogin folder with following contents:
<?php
session_start();
require_once "Facebook/autoload.php";

$FB = new \Facebook\Facebook([
      'app_id' => 'REPLACE_APP_ID',
      'app_secret' => 'REPLACE_APP_SECRET',
      'default_graph_version' => 'v2.10',
      ]);

$helper = $FB->getRedirectLoginHelper();
?>
(4) For getting app_id, app_secret and app_version, we go to https://developers.facebook.com/apps and create a new app. In the Settings tab, we can find the required info which we have to copy and paste. In the Settings tab, we give App Domains as ‘localhost’ and platform website URL as ‘https://localhost/FacebookLogin/’. [Note that since March 2018, we have to use https for interacting with Facebook. So we must have https enabled in localhost and working.]
(5) Now, we need to make a page where people will be redirected from Facebook (say fb-callback.php) with the following contents:
<?php
      require_once "config.php";
      try {
                  $accessToken = $helper->getAccessToken(); //short lived token

      } catch(\Facebook\Exceptions\FacebookResponseException $e) {
                  echo "Response Exception :" . $e->getMessage();
                  exit();
      } catch(\Facebook\Exceptions\FacebookSDKException $e) {
                  echo "SDK Exception :" . $e->getMessage();
                  exit();
      }

      if (!$accessToken) {
                  header('Location: login.php');
                  exit();
      }

$oAuth2Client = $FB->getOAuth2Client();
if (!$accessToken->isLongLived())
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);

$response = $FB->get
("me?fields=id,first_name,last_name,email,picture.type(large)",  
$accessToken);

      $userData = $response->getGraphNode()->asArray();
      //echo "<pre>";
      //var_dump($userData);//we get all info and url of the picture
      $_SESSION['userData'] = $userData;
      $_SESSION['access_token'] = (string) $accessToken;
      header("Location: index.php");
      exit();
?>
(6)   Next, we create a login.php file where there is option for user to ‘Log in with Facebook’.
<?php
require_once "config.php";
if (isset($_SESSION['access_token'])) {
      header("Location: index.php");
      exit();
}
$redirectURL = "https://localhost/FacebookLogin/fb-callback.php";
$permissions = ['email'];
$loginURL = $helper->getLoginUrl($redirectURL, $permissions);
// echo $loginURL;
?>

<!DOCTYPE html>
<html>
<head>
      <title>Log In</title>
<link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

</head>
<body>
  <div class="container" style="margin-top: 100px">
      <div class="row justify-content-center">
          <div class="col-md-6 col-md-offset-3" align="center">
              <img src="Images/logo.jpg"><br><br>
             <form>
              <input type="email" name="email" placeholder = "Email" 
              class = "form-control"><br>
              <input type = "password" name = "password" 
              placeholder = "Password" class = "form-control"><br>
              <input type="submit" name="submit" value="Log In" 
              class = "btn btn-primary">
              <input type="button" onclick="window.location='<?php 
              echo $loginURL; ?>';" name = "submit" 
              value="Log In With Facebook" class="btn btn-primary">
          </form>
        </div>
      </div>
    </div>
</body>
</html>
(7)   Next, we create “index.php” where a Facebook authenticated user will be redirected and display his Facebook data.
<?php
session_start();
if (!isset($_SESSION['access_token'])) {
      header("Location: login.php");
      exit();
}

?>
<!DOCTYPE html>
<html>
<head>
      <title>User Profile</title>
      <link rel="stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
</head>
<body>
  <div class="container" style="margin-top: 100px">
      <div class="row justify-content-center">
          <div class="col-md-3">
           <img src="<?php echo $_SESSION['userData']['picture']['url']; ?>">     
          </div>
          <div class="col-md-9">
              <table class="table table-hover table-bordered">
                  <tbody>
                      <tr>
                        <td>ID</td>
                        <td><?php echo $_SESSION['userData']['id']; ?></td>
                      </tr>
                      <tr>
                      <td>First Name</td>
                     <td><?php echo $_SESSION['userData']['first_name']; ?></td>
                      </tr>
                      <tr>
                        <td>Last Name</td>
                       <td><?php echo $_SESSION['userData']['last_name']; ?></td>
                      </tr>
                      <tr>
                        <td>Email</td>
                        <td><?php echo $_SESSION['userData']['email']; ?></td>
                      </tr>
                   </tbody>
                 </table>
              </div>
          </div>
    </div>
</body>
</html>
(8) Finally, we need to enable “Embedded Browser OAuth Login” and give the URL “https://localhost/FacebookLogin/fb-callback.php” for “Valid OAuth Redirect URIs” in the Settings of our “Facebook Login” app in https://developers.facebook.com.
(9) Now, we can run the ‘login.php’ file and successfully Log in with Facebook. The code can be downloaded from GitHub.


2 comments: