Need to gohttps://developers.facebook.com/apps/ and click on add a new group button to make the app ID.

  • Choose Website
  • Give an app name and click on Create New Facebook App ID
  • Click on Create app ID
  • Click on Skip Quick Test

Then create composer.json to instsall facebook php-sdk

#composer.json

{
    "require": {
        "facebook/graph-sdk": "^5.6"
    }
}

Open command window & run the following composer command composer install, it will download all the pageckes 

Composer install command


#fb_init.php

<?php

//start the session
session_start();

//include autoload file from vendor folder
require './vendor/autoload.php';


$fb = new Facebook\Facebook([
    'app_id' => '', // replace your app_id
    'app_secret' => '',   // replace your app_scsret
    'default_graph_version' => 'v2.7'
        ]);


$helper = $fb->getRedirectLoginHelper();
$login_url = $helper->getLoginUrl("http://localhost/fb-login/");

try {

    $accessToken = $helper->getAccessToken();
    if (isset($accessToken)) {
        $_SESSION['access_token'] = (string) $accessToken;  //conver to string
        //if session is set we can redirect to the user to any page 
        header("Location:index.php");
    }
} catch (Exception $exc) {
    echo $exc->getTraceAsString();
}


//now we will get users first name , email , last name
if (isset($_SESSION['access_token'])) {

    try {

        $fb->setDefaultAccessToken($_SESSION['access_token']);
        $res = $fb->get('/me?locale=en_US&fields=name,email');
        $user = $res->getGraphUser();
        echo 'Hello, ',$user->getField('name');
        
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

#index.php

<?php require './fb-init.php'; ?>

<?php if (isset($_SESSION['access_token'])): ?>
<a href="logout.php">Logout</a>
<?php else: ?>
    <a href="<?php echo $login_url; ?>">Login With facebook</a>
<?php endif; ?>

#logout.php

<?php
include './fb-init.php';
session_destroy();
unset($_SESSION['access_token']);
header("Location:index.php");
?>


Download source code

Are you facing problems in understanding this article? download source code now