Login with Facebook API SDK v5 in PHP - Mostlikers

14 February, 2017

Login with Facebook API SDK v5 in PHP

The Facebook SDK for PHP is a library with capable elements that empower PHP designers to effortlessly incorporate Facebook login and make solicitations to the Graph API. Today we are going to see how to log in with facebook API SDK v5 in PHP. Facebook SDK old version some response are deprecated. Now use should follow the latest version of SDK V5, It will be more efficient and extend a powerful class. Follow the below script implement facebook latest version SDK.




Live Demo              Download

For using new SDK version you can get the more information about the user.
  • Retrieve User’s Profile Information like id, email, birthday
  • Get User’s Profile Picture based on large, medium, small size image
  • Publish to User’s Timeline Like share button process.
  • Retrieve User’s Timeline based on their profile privacy.
  • Upload a File Photo, Video user timeline.
How to create the app and implement complete video tutorial.
Link: https://www.youtube.com/watch?v=UlqCL-I6jYw

1.First, create the facebook app and get the app secret id and key.

Once created the app you will get some unique id and key. For getting more about create facebook watch a youtube video.

Now create a new folder in your host, Download latest version SDK file. Extract with your local path.

Complete guidelines video


facebook_config.php

Create a new file called facebook_config.php. include the  SDK new version code and set the config of your facebook app.
<?php
session_start();
require_once __DIR__ . '/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
  'app_id' => '********', // Replace {app-id} with your app id
  'app_secret' => '*********',
  'default_graph_version' => 'v2.2',
]);
?>

Database

Create a new table called 'facebook_users' with the below structure column.This table we will store facebook users response.
CREATE TABLE `facebook_users` (
  `id` int(11) NOT NULL,
  `oauth_id` varchar(100) NOT NULL,
  `name` varchar(50) NOT NULL,
  `email` varchar(100) NOT NULL,
  `gender` varchar(5) NOT NULL,
  `picture` varchar(250) NOT NULL,
  `link` varchar(250) NOT NULL,
  `cover` varchar(300) NOT NULL,
  `last_update` timestamp NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Database Connection

Create a new file 'db_config.php' for database connection.Set your database connection.
<?php  
    $db = new mysqli("localhost","user","password","database");
    if (mysqli_connect_errno()) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
?>  

Index.php

Create a new index file include facebook config file. this page will check the user response information. In case your access token already exists the session, the page will be redirected to profile page.
<?php
include_once("facebook_config.php");
if(!isset($_SESSION['fb_access_token'])) : 
    $helper = $fb->getRedirectLoginHelper();
    $permissions = ['email'];
    $redirect = 'http://yourhost/yourfolder/fb-callback.php';
    $loginUrl = $helper->getLoginUrl($redirect,$permissions);
    echo '<a href="' . htmlspecialchars($loginUrl) . '">Login with Facebook!</a>';
else :
    header('Location: member.php');
endif;
?>

FB-callback.php

After getting the facebook response, We are storing the particular user access token to the session. Because based the access token only we can get the facebook user response.
<?php
include_once("facebook_config.php");
$helper = $fb->getRedirectLoginHelper();
try {
  $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

if (! isset($accessToken)) {
  if ($helper->getError()) {
    header('HTTP/1.0 401 Unauthorized');
    echo "Error: " . $helper->getError() . "\n";
    echo "Error Code: " . $helper->getErrorCode() . "\n";
    echo "Error Reason: " . $helper->getErrorReason() . "\n";
    echo "Error Description: " . $helper->getErrorDescription() . "\n";
  } else {
    header('HTTP/1.0 400 Bad Request');
    echo 'Bad request';
  }
  exit;
}

// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';
echo '<pre>'; print_r($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId("1721283891461664"); // Replace {app-id} with your app id
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (! $accessToken->isLongLived()) {
  // Exchanges a short-lived access token for a long-lived one
  try {
    $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
  } catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
    exit;
  }

  echo '<h3>Long-lived</h3>';
  var_dump($accessToken->getValue());
  echo '<pre>'; print_r($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;

// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.
header('Location:member.php');
?>

member.php

$fb->get() this function it will get the particular user response based on their access token.
<?php
include_once("db_config.php");
include_once("facebook_config.php");
if(!isset($_SESSION['fb_access_token'])) :
    $helper = $fb->getRedirectLoginHelper();
    $permissions = ['email'];
    $redirect = 'http://localhost/demo/sales/facebook/fb-callback.php';
    $loginUrl = $helper->getLoginUrl($redirect,$permissions);
    echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';
else :
  $user_token = $_SESSION['fb_access_token'];
  try {
    $response = $fb->get('/me?fields=id,name,email,birthday,gender,picture,cover,link',
$user_token);
  } 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;
  }
  $user = $response->getGraphUser();
  $profile = $user->getPicture();
  $oauth_id = $user["id"];
  $user_information  = array(
    'name'    => $user["name"],
    'email'   => $user["email"],
    'gender'  => $user["gender"],
    'picture' => $user['picture']['url'],
    'link'    => $user["link"],
    'cover'   => $user['cover']['source']
  );
?>


Users information

After getting the response from facebook. store the user information to the database. if the user data already exists the just update the user information.

$user_check = $db->query("SELECT oauth_id FROM facebook_users WHERE oauth_id=$oauth_id");
  $user_check_count = mysqli_num_rows($user_check);
  if($user_check_count) :
    $update =$db->query("UPDATE `facebook_users` SET `name`='".$user_information['name']."',`email`='".$user_information['email']."',
      `gender`='".$user_information['gender']."',`picture`='".$user_information['picture']."',
      `link`='".$user_information['link']."',`cover`='".$user_information['cover']."' WHERE oauth_id ='".$oauth_id."'");
  else :
    $insert = $db->query("INSERT INTO `facebook_users` SET `oauth_id`='".$oauth_id."', `name`='".$user_information['name']."',
      `email`='".$user_information['email']."',`gender`='".$user_information['gender']."',`picture`='".$user_information['picture']."',`link`='".$user_information['link']."',`cover`='".$user_information['cover']."'");
  endif;
  $query_user = $db->query("SELECT * FROM facebook_users WHERE oauth_id=$oauth_id");
  $user_data = mysqli_fetch_assoc($query_user);
  echo '<pre>'; print_r($user_data); exit;

logout.php

Unset the access token session value.
<?php
    session_start();
    session_unset($_SESSION['fb_access_token']);
    header("Location:index.php");
?>


Reference

All the above PHP code and SDK file everything I have referred facebook site.

No comments:

Post a comment