Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PHP

Integrating Facebook Account into a Log-in Session

5.00/5 (4 votes)
23 May 2014CPOL3 min read 38K   770  
An example of log-in system with Facebook API v.4

Introduction

In the previous tip, Creating a Log-in Session in PHP, I have created a login with an account assuming stored in a database on the Web hosting server. In many cases, to make it convenient for the users, we might want to use Facebook account instead.

This project includes the Facebook account integration into, and also some changes/improvements to the previous one.

First Step

First of all, visit Facebook App Dashboard - Facebook Developers to create a new app. The process is simple, but there are some things to consider:

In the Settings section:
  • Platform is: Website
  • Site URL: something like this: http://todaythoughts.com/ (ends with '/', and without sub-directories even if your project folder is in sub-directory. Change to use your domain name)
  • App Domains: just this: todaythoughts.com

In the Status & Review section: make sure you check 'YES' for the question 'Do you want to make this app and all its live features available to the general public?'

In the Dashboard section, remember the App ID and App Secret. You will need these two later.

Image 1

Set-up the Project

Download the Facebook PHP SDK on GitHub. Extract to get the Facebook folder inside src folder. Copy this Facebook folder into the project root folder.
Image 2

The Code

It's recommended to read the previous tip (link on top of this page). When adding Facebook functionality to this project, I had to spend time learning what I had done before.

The loginFB.php is the single heavy lifting to do all the work related to Facebook.

loginFB.php must include classes needed first:

PHP
ob_start();
session_start();
// include required files form Facebook SDK
// added in v4.0.5
require_once( 'Facebook/FacebookHttpable.php' );
require_once( 'Facebook/FacebookCurl.php' );
require_once( 'Facebook/FacebookCurlHttpClient.php' );

// added in v4.0.0
require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookOtherException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
require_once( 'Facebook/GraphSessionInfo.php' );

// added in v4.0.5
use Facebook\FacebookHttpable;
use Facebook\FacebookCurl;
use Facebook\FacebookCurlHttpClient;
// added in v4.0.0
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;

Next is to initial app with App ID and App Secret you have got from your dashboard:

PHP
$id = '?'; // please use yours
$secret = '?'; // please use yours
FacebookSession::setDefaultApplication($id, $secret);

$helper = new FacebookRedirectLoginHelper('http://todaythoughts.com/CS4880FB/loginFB.php');

The following portion of code is not much important but useful to remember if the user had logged in and so to store the existing valid session:

PHP
// see if a existing session exists
if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
    // create new session from saved access_token
    $session = new FacebookSession($_SESSION['fb_token']);
    // validate the access_token to make sure it's still valid
    try {
        if (!$session->validate()) {
            $session = null;
        }
    } catch (Exception $e) {
        // catch any exceptions
        $session = null;
    }
} else {
    // no session exists
    try {
        $session = $helper->getSessionFromRedirect();
    } catch (FacebookRequestException $ex) {
        // When Facebook returns an error
    } catch (Exception $ex) {
        // When validation fails or other local issues
        echo $ex->message;
    }
}

Now, this last portion of code is what we need to pay more attention:

PHP
// see if we have a session
if (isset($session)) {
    // save the session
    $_SESSION['fb_token'] = $session->getToken();
    // create a session using saved token or the new one we generated at login
    $session = new FacebookSession($session->getToken());
    // graph api request for user data
    $request = new FacebookRequest($session, 'GET', '/me');
    $response = $request->execute();
    $graphObject = $response->getGraphObject()->asArray();

    $_SESSION['valid'] = true;
    $_SESSION['timeout'] = time();

    $_SESSION['FB'] = true;

    $_SESSION['usernameFB'] = $graphObject['name'];
    $_SESSION['idFB'] = $graphObject['id'];
    $_SESSION['first_nameFB'] = $graphObject['first_name'];
    $_SESSION['last_nameFB'] = $graphObject['last_name'];
    $_SESSION['genderFB'] = $graphObject['gender'];

    // logout and destroy the session, redirect url must be absolute url
    $linkLogout = $helper->getLogoutUrl($session, 'http://todaythoughts.com/CS4880FB/redirect.php?action=logout');

    $_SESSION['logoutUrlFB'] = $linkLogout;
    header('Location: index.php');
} else {
    header('Location: ' . $helper->getLoginUrl());
}

As we saw, $graphObject is stored as an associate array to provide pieces of a Facebook account information, such as first name, or gender, to assign to corresponding $_SESSION variables.

That we are done with the loginFB.php. The file header.php has the code portion:

PHP
if (isset($_SESSION['FB']) && ($_SESSION['FB']) == true) {
    if (isset($_SESSION['valid']) && $_SESSION['valid'] == true) {
        // echo $_SESSION['usernameFB']
        // echo <a href="' . $_SESSION['logoutUrlFB'] . '">Logout FB</a>
    } else {
        echo '<a href="loginFB.php">Login with Facebook';
    }
} else {
    echo '<a href="loginFB.php">Login with Facebook</a>';
}

Also refer to the loginFB.php, when we click to log-in, the page transfers to Facebook log-in page ($helper->getLoginUrl()). If the user successfully logged-in, the page is re-directed to index.php page.

In case the user decides to log-out, the variable $_SESSION['logoutUrlFB'] will be used. The page to be re-directed to the page redirect.php?action=logout, and be re-directed again there to index.php.

redirect.php is a 'control center' to re-direct pages based on the $_GET variables:

PHP
$msg = '';
if (isset($_GET['action'])) {
    if ($_GET['action'] == 'succeed') {
        $msg = 'Logged successfully...';
        echo '<p class="lead">' . $msg . '</p>';
        header('Refresh: 2; URL=index.php');
    } else if ($_GET['action'] == 'timeover') {
        session_unset();
        session_destroy();
        $msg = 'Inactivity so long, now need to sign-in again.';
        echo '<p class="lead">' . $msg . '

';
        header('Refresh: 2; URL=login.php');
    } else if ($_GET['action'] == 'logout') {
        session_unset();
        session_destroy();
        $msg = 'Logged out. Now come back to homepage';
        echo '<p class="lead">' . $msg . '
';
        header('Refresh: 2; URL=index.php');
    } else if ($_GET['action'] == 'invalid_permission') {
        session_unset();
        session_destroy();
        $msg = 'Invalid permission. Come back to homepage...';
        echo '
</p><p class="lead">' . $msg . '
';
        header('Refresh: 2; URL=index.php');
    }
} else {
    header('Location: index.php');
}

For example, when the time period since logging in becomes greater than 1 hour, the redirect.php will take care of that:

PHP
if (isset($_SESSION['valid']) && $_SESSION['valid'] == true) {
    $inactive = 60 * 60 * 1;
    if (time() - $_SESSION['timeout'] > $inactive) {
        header('Location: redirect.php?action=timeover');
    } else {
        if (isset($_SESSION['username'])) {
            // echo $_SESSION['username'];
            // echo <a href="redirect.php?action=logout">Logout</a>
        }
    }
} else {
    echo '<a href="login.php">Login';
}

What's Next?

How about Google, Yahoo, Linkin, and many more? It is lots of work to maintain them. So I guess a Social Sign On Library, such as HybridAuth would be a better choice (?)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)