Skip to content

Instantly share code, notes, and snippets.

@SteffanLong
Forked from niraj-shah/fb_4.0.x.php
Last active August 29, 2015 14:02
Show Gist options
  • Save SteffanLong/7337c82fc2e6ac34ca44 to your computer and use it in GitHub Desktop.
Save SteffanLong/7337c82fc2e6ac34ca44 to your computer and use it in GitHub Desktop.
<?php
// require the Composer autoload
require 'vendor/autoload.php';
// start session
session_start();
// init app with app id and secret
Facebook\FacebookSession::setDefaultApplication('APP_ID', 'APP_SECRET');
// create new redirect login helper
// use destination URL to redirect to after login
$helper = new Facebook\FacebookRedirectLoginHelper('http://example.com/');
// see if a existing session exists
if (isset($_SESSION) && isset($_SESSION['fb_token']))
{
// create new session from saved access_token
$session = new Facebook\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(Facebook\FacebookRequestException $e) {
// When Facebook returns an error
// handle this better in production code
print_r($e);
} catch(Exception $e) {
// When validation fails or other local issues
// handle this better in production code
print_r($e);
}
}
// 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 Facebook\FacebookSession($session->getToken());
// graph api request for user data
$request = new Facebook\FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject(Facebook\GraphUser::className());
// print profile data
echo '<pre>' . print_r($graphObject, 1) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo '<a href="' . $helper->getLogoutUrl($session, 'http://example.com/logout.php') . '">Logout</a>';
} else {
// show login url
// pass required scope here
echo '<a href="' . $helper->getLoginUrl(array('email', 'user_friends')) . '">Login</a>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment