PHP Facebook Login And Integration in PHP Website Tutorial

This tutorial explains how to integrate and Login in Facebook through PHP.

In this tutorial, we will learn how to login or synchronize from any Website or Web Pages through Facebook Account. For that, We will use PHP for the back end to connect Facebook. We will create a login button. When user clicks on the login button then a Facebook dialog box open to integrate user Facebook account to App and its return user information to use login in our website.

Login to Facebook for Developer

Don't Miss

Facebook provides facility for developer to create an App ID to integrate Any Android Application. Hence, we need to login in Facebook for Developer

Create App to Facebook Developer Account

After Facebook Login for developer account, We need to create an App Id to integrate facebook with Android Application.

  • Click on the Create App button top of the Page.
  • To create a New App ID, enter display name of Application, contact email id. Click on Create App Id button.

Product Setup

Product Setup
Don't Miss

We created App Id. Now to setup Facebook product, here we are going to login with Facebook in our Android Application. Hence we will click on the Get Started button in the Facebook Login Menu.

Choose a Platform

This tutorial explains about integrating Facebook to PHP. Hence we need to click on the Web.

Tell Us about Your Website

Fb_tell_us_about_website

Fill the your site url in the Site URL section. Click on the save and continue button.

Make App Public(Live)

We need to live our App means make public. It will become available to everyone.

  • Click on the App Review menu
  • Click on the No button
  • Choose App Category and click on the confirm button

Enable Client OAuth login

oAuthEnabled

To open dialog box to login from Facebook, we need to enable Embedded Browser OAuth Login and fill the OAuth url. When user integrate successfully with Facebook Account then redirect to OAuth url in which we get user details.

Update Website information

To make app publicly, we need to update some website information.Click on the Settings menu and save some input field such as App Domains,Privacy Policy URL, Terms of Service URL & upload App Icon. Without save these information your App not working properly.

facebook Setting

Download Facebook SDK

To integrate Facebook, we need to download Facebook SDK ZIP file. Unzip downloaded Facebook SDK ZIP file and move it in your project.

Login Button

Facebook Login Button

We will create a simple login button to login with facebook. On Click this button, we will use Facebook SDK to integrate Facebook User account to your App.

Facebook Login

We will create a new PHP file – fblogin.php. In this file, we will include Facebook SDK. Make sure Facebook SDK path is correct. Create a new object as Facebook and pass the App ID, App secret Key and App version. Call the getRedirectLoginHelper() method to get redirect login url object. Use the Access token to get User details. When user click on the login button then a dialog box open to integrate Facebook account to APP.

<php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set('memory_limit', '-1');

// Include the autoloader provided in the SDK
require_once __DIR__ . '/facebook-php-sdk/autoload.php';

// Include required libraries
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;

$appId = 'YOUR APP ID'; //Facebook App ID
$appSecret = 'YOUR APP SECRET KEY'; //Facebook App Secret
$redirectURL = 'YOUR CALLBACK URL'; //Callback URL
$fbPermissions = array('email');  //Optional permissions

$fb = new Facebook(array(
'app_id' => $appId,
'app_secret' => $appSecret,
'default_graph_version' => 'v2.9',
));

// Get redirect login helper
$helper = $fb->getRedirectLoginHelper();

// Try to get access token
try {
// Already login
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}

if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// Put short-lived access token in session
$_SESSION['facebook_access_token'] = (string) $accessToken;

// OAuth 2.0 client handler helps to manage access tokens
$oAuth2Client = $fb->getOAuth2Client();

// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;

// Set default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}

// Redirect the user back to the same page if url has "code" parameter in query string
if (isset($_GET['code'])) {

// Getting user facebook profile info
try {
$profileRequest = $fb->get('/me?fields=name,first_name,last_name,email,link,gender,locale,picture');
$fbUserProfile = $profileRequest->getGraphNode()->asArray();
// Here you can redirect to your Home Page.
print_r($fbUserProfile);
} catch (FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// Redirect user back to app login page
header("Location: ./");
exit;
} catch (FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
} else {
// Get login url

$loginURL = $helper->getLoginUrl($redirectURL, $fbPermissions);
header("Location: " . $loginURL);

}
} catch (FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}

?>
Facebook Login dialog boxlogin_success

17 COMMENTS

  1. Getting a fatal error,
    Facebook SDK returned an error: Access token was not returned from Graph.

    Going in else part
    if (isset($_SESSION[‘facebook_access_token’])) {
    $accessToken = $_SESSION[‘facebook_access_token’];
    } else {
    $accessToken = $helper->getAccessToken();
    }
    I print this above if and get this FATAL error,

    Fatal error: Uncaught exception ‘FacebookExceptionsFacebookSDKException’ with message ‘Access token was not returned from Graph.’ in E:xampphtdocsrkrtutorial.comfacebookloginfacebook-php-sdkAuthenticationOAuth2Client.php:230 Stack trace: #0 E:xampphtdocsrkrtutorial.comfacebookloginfacebook-php-sdkAuthenticationOAuth2Client.php(166): FacebookAuthenticationOAuth2Client->requestAnAccessToken(Array) #1 E:xampphtdocsrkrtutorial.comfacebookloginfacebook-php-sdkHelpersFacebookRedirectLoginHelper.php(255): FacebookAuthenticationOAuth2Client->getAccessTokenFromCode(‘AQDCZip2NnKFzl0…’, ‘http://rkrtutor…’) #2 E:xampphtdocsrkrtutorial.comfacebookloginfacebooklogin.php(32): FacebookHelpersFacebookRedirectLoginHelper->getAccessToken() #3 {main} thrown in E:xampphtdocsrkrtutorial.comfacebookloginfacebook-php-sdkAuthenticationOAuth2Client.php on line 230

  2. Hy, i was insert facebook login in a custom platform.. html php.. but after user is login with facebook she dosen’t have an account acces…, i need to insert user in database website ? after that she will have acces to account ?

    • In this tutorial, I have also written code to get user details like name,first_name,last_name,email,link,gender,locale,picture.

  3. help me …
    this is error
    Insecure Login Blocked: You can’t get an access token or log in to this app from an insecure page. Try re-loading the page as https://

  4. Hello, When I used the above code, I am not getting access token and its always take to me on else part where it redirect automatically but I want to show the all details of logged in user.
    Thanks

  5. Graph returned an error: Can’t Load URL: The domain of this URL isn’t included in the app’s domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

  6. i am working on a website in which i want to allow user to simply chat with each other but their chat should be hidden from other users..
    like Registered users on web,
    1. you
    2.me

    you send me hii ..
    now i reply you hello..

    $sql= insert into table where sender = $_SESSION[‘user’] and receiver= $_GET[‘user’];
    now table ->
    id- 1
    sender id – 1
    receiver id – 2
    message – hii

    id- 2
    sender id – 2
    receiver id – 1
    message – hello

    now fetch data in message box,
    $sql= select from table where receiver= $_SESSION[‘user’] and sender= $_GET[‘user’];

    but this is garbage output…

    how should i fetch message then i conversation properly.. please help me , i will be very thankful to you..

    sorry for bad English….

LEAVE A REPLY

Please enter your comment!
Please enter your name here

564FansLike

Recent Posts

How to create ListView using Adapter in Android Tutorial

In this tutorial, we're explaining the way to create ListView in Android Application. What is Android ListView? Android ListView is a view which teams a number...

Basic Geometry Math Formula List

Geometry is a department of mathematics that offers with shape, dimension, relative position of figures, and the properties of space. It emerges independently in variety of early cultures as a practical approach of dealing with lengths, area and volumes.

How to Sign in with Google in Android Tutorial

In this tutorial, we are going to explain how to sign in with Google in Android Application. Many apps want to...

Related Articles

How to create ListView using Adapter in Android Tutorial

In this tutorial, we're explaining the way to create ListView in Android Application. What is Android ListView? Android ListView is a view which teams a number...

Basic Geometry Math Formula List

Geometry is a department of mathematics that offers with shape, dimension, relative position of figures, and the properties of space. It emerges independently in variety of early cultures as a practical approach of dealing with lengths, area and volumes.

How to Sign in with Google in Android Tutorial

In this tutorial, we are going to explain how to sign in with Google in Android Application. Many apps want to...