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.
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.
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:
ob_start();
session_start();
require_once( 'Facebook/FacebookHttpable.php' );
require_once( 'Facebook/FacebookCurl.php' );
require_once( 'Facebook/FacebookCurlHttpClient.php' );
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' );
use Facebook\FacebookHttpable;
use Facebook\FacebookCurl;
use Facebook\FacebookCurlHttpClient;
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:
$id = '?';
$secret = '?';
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:
if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
$session = new FacebookSession($_SESSION['fb_token']);
try {
if (!$session->validate()) {
$session = null;
}
} catch (Exception $e) {
$session = null;
}
} else {
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
} catch (Exception $ex) {
echo $ex->message;
}
}
Now, this last portion of code is what we need to pay more attention:
if (isset($session)) {
$_SESSION['fb_token'] = $session->getToken();
$session = new FacebookSession($session->getToken());
$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'];
$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:
if (isset($_SESSION['FB']) && ($_SESSION['FB']) == true) {
if (isset($_SESSION['valid']) && $_SESSION['valid'] == true) {
} 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:
$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:
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'])) {
}
}
} 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 (?)