Facebook SDK 4.0.0 for PHP: A working sample to manage sessions

By | May 10, 2014

 

Once you have a working sample of Facebook SDK 4.0.0 for PHP, you will notice upon refreshing the page an error:
Fatal error: Uncaught exception ‘Facebook\FacebookAuthorizationException’ with message ‘This authorization code has expired.’

Well, this is quite annoying as it breaks the user navigation on your site. To get around this issue, record the FacebookSession token to the user’s session and use it next time the page load.

[php]
<?php
session_start();

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/FacebookAuthorizationException.php’ );
require_once( ‘Facebook/GraphObject.php’ );
require_once( ‘Facebook/GraphSessionInfo.php’ );

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;

$appid = ”; // your AppID
$secret = ”; // your secret

// Initialize app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication($appid ,$secret);

// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( ‘http://www.metah.ch/’ );

try
{
// In case it comes from a redirect login helper
$session = $helper->getSessionFromRedirect();
}
catch( FacebookRequestException $ex )
{
// When Facebook returns an error
echo $ex;
}
catch( Exception $ex )
{
// When validation fails or other local issues
echo $ex;
}

// see if we have a session in $_Session[]
if( isset($_SESSION[‘token’]))
{
// We have a token, is it valid?
$session = new FacebookSession($_SESSION[‘token’]);
try
{
$session->Validate($appid ,$secret);
}
catch( FacebookAuthorizationException $ex)
{
// Session is not valid any more, get a new one.
$session =”;
}
}

// see if we have a session
if ( isset( $session ) )
{
// set the PHP Session ‘token’ to the current session token
$_SESSION[‘token’] = $session->getToken();
// SessionInfo
$info = $session->getSessionInfo();
// getAppId
echo "Appid: " . $info->getAppId() . "<br />";
// session expire data
$expireDate = $info->getExpiresAt()->format(‘Y-m-d H:i:s’);
echo ‘Session expire time: ‘ . $expireDate . "<br />";
// session token
echo ‘Session Token: ‘ . $session->getToken() . "<br />";
}
else
{
// show login url
echo ‘<a href="’ . $helper->getLoginUrl() . ‘">Login</a>’;
}
?>
[/php]

The session expire time (getExpiresAt()) can be used to monitor how long the token can be used and potentially request a new token.

 
3 Kudos
Don't
move!

18 thoughts on “Facebook SDK 4.0.0 for PHP: A working sample to manage sessions

  1. Deepak Sharma

    Hey Ahmet, Thanks for this perfect example. This worked for me in first go. But, I want to get the list of all the friends of the logged in user for which I am trying to use “/{friendlist-id}/members” (I am getting the list id by first requesting “/me/friendlists”). But the former always gives me an empty array. I have searched everywhere for past two days and your article is the only one i found which discusses usage of php sdk 4.0 correctly. So, if can spare out a few minutes, please help me figure out some way to solve it.

    Reply
    1. Ahmet Post author

      Hey Deepak, please share your code snippet, I can get a look.

      Reply
      1. Ashish Chaturvedi

        Hi Ahment.Thanks for this nice work. As deepak mention in his comment getting an empty error when i want to get friends lists.
        My tries here:-

        if ( isset( $session ) ) {
        // graph api request for user data
        $request = new FacebookRequest( $session, ‘GET’, ‘/me/friends’ );
        $response = $request->execute();
        // get response
        $graphObject = $response->getGraphObject();

        // print data
        echo print_r( $graphObject, 1 );
        } else {
        // show login url
        echo ‘getLoginUrl() . ‘”>Login‘;
        }

        Reply
  2. Aswin Lutchanah

    Thank you for your article. The 4.0 version seems to have more options but the documentation is not that clear…
    I’ve spent a few hours on this too 😉
    Take Care

    Reply
  3. Rafi

    Thanks for the article, I don’t know why but it is redirecting me to the redirect url I’ve set with the code as “http://www.xxxxxx.com/code=zzzzzzzzzzzzzz
    and it stays there.
    what should I do next?
    If I refresh the php file I see again the Login button…

    Am I missing something?

    Thanks in advance.

    Reply
    1. Neil Young

      I get the same problem and still cannot figure it out. Is this a problem with Facebook’s SDK? I have logged a bug but they keep closing it!

      Reply
  4. Charbel

    I think something strange happens, I’ve set the ‘user_friends’ permissions and went to debug the tokenId in https://developers.facebook.com/tools/explorer/

    I can see the scope as below
    Scopes = public_profile, basic_info, email, user_birthday, user_friends

    and still getting empty array in /me/friends

    same code as @Ashish.

    Reply
  5. joris

    I tried this and it does not quite work for me.
    I’m building a FB tab page and on the landings page, I can successfully set up a FacebookSession using the signed_request.
    I store the token in the started session.

    When I navigate to another PHP page in the IFrame, where another FacebookSession is created using the token in the session, the SDK throws a “Session has expired, or is not valid for this app”-error.

    Any ideas?

    Reply
  6. Sharmi Sharmi

    i have used your code to post a message on facebook wall (in my fabcebook timeline)

    I am able to read my profile but not able to post a message into facebook account,

    getSessionFromRedirect();
    }
    catch( FacebookRequestException $ex )
    {
    // When Facebook returns an error
    echo $ex;
    }
    catch( Exception $ex )
    {
    // When validation fails or other local issues
    echo $ex;
    }

    // see if we have a session in $_Session[]
    if( isset($_SESSION[‘token’]))
    {
    // We have a token, is it valid?
    $session = new FacebookSession($_SESSION[‘token’]);
    try
    {
    $session->Validate($appid ,$secret);
    }
    catch( FacebookAuthorizationException $ex)
    {
    // Session is not valid any more, get a new one.
    $session =”;
    }
    }

    // see if we have a session
    if ( isset( $session ) )
    {
    // set the PHP Session ‘token’ to the current session token
    $_SESSION[‘token’] = $session->getToken();
    // SessionInfo
    $info = $session->getSessionInfo();
    // getAppId
    echo “Appid: ” . $info->getAppId() . “”;
    // session expire data
    $expireDate = $info->getExpiresAt()->format(‘Y-m-d H:i:s’);
    echo ‘Session expire time: ‘ . $expireDate . “”;
    // session token
    echo ‘Session Token: ‘ . $session->getToken() . “”;

    /* I am trying to read my information */

    if($session) {

    try {

    $user_profile = (new FacebookRequest(
    $session, ‘GET’, ‘/me’
    ))->execute()->getGraphObject(GraphUser::className());

    echo “Name: ” . $user_profile->getName();

    } catch(FacebookRequestException $e) {

    echo “Exception occured, code: ” . $e->getCode();
    echo ” with message: ” . $e->getMessage();

    }

    }

    /* I am trying to write into my timeline */

    if($session) {

    try {

    $response = (new FacebookRequest(
    $session, ‘POST’, ‘/me/feed’, array(
    ‘link’ => ‘www.example.com’,
    ‘message’ => ‘User provided message’
    )
    ))->execute()->getGraphObject();

    echo “Posted with id: ” . $response->getProperty(‘id’);

    } catch(FacebookRequestException $e) {

    echo “Exception occured, code: ” . $e->getCode();
    echo ” with message: ” . $e->getMessage();

    }

    }

    }
    else
    {
    // show login url
    echo ‘getLoginUrl(array(‘redirect-uri’=>$returnurl, ‘scope’=>$permissions)) . ‘”>Login‘;
    }
    ?>

    when execute my fb1.php page,

    I am getting following response.
    it means, i am able to get read my profile name
    but not able to post message into my timeline.

    Session Token: CAAEsnhOByoUBAIz89P1ZAgW4n23aod60PI8aOWZAYG7OCL7U5ptQnoWqNF5jou8ceu6MGyYyP05IQkGZCKCZCUjKfpVlXKyKNjbN5gBli9pZBxZCAHzZBMZC29fiYMPv3L8PJo5c9p67cquxQbkUddkDfOSHZCMF96tBLEzdXGjFvMPzAj6H5JHNlszX4JsZAqb18aAhfejg241CTiulKkoYlr
    Name: Sharmi SharmiException occured, code: 200 with message: (#200) Permissions error

    in my app, i have granted the permission, to all to post in my timline,

    {

    “name”: “Sharmi Sharmi”,
    “permissions”: {
    “data”: [
    {
    “permission”: “public_profile”,
    “status”: “granted”
    },
    {
    “permission”: “publish_actions”,
    “status”: “granted”
    }
    ]
    }
    }

    don’t know, how to post a message on my timeline.
    I have tried the app in a live mode and changed it to normal one but still i am not able to post a message.

    can you help me ?

    Reply
  7. Max Carroll

    HI should the redirect url be the same as the file in which it is written? e.g if this file is called test.php then that should be the redirect url too? or do we need it to be a seperate page?

    Reply
  8. Pingback: Facebook v4.4 PHP SDK 升級範例 - Tsung's Blog

  9. Matt

    hi there,

    very well structured example!

    how would you catch exceptions from this line?
    “FacebookSession::setDefaultApplication($appid ,$secret);”

    I didnt find a way to use the existing exception classes to handle errors like an outdated token or invalid app ID.

    thank you
    Mathias

    Reply
  10. Magesh

    Hi,

    I have tried many ways with many sample code which you a posted.But still now session values return as NULL.Please help .I cant figure out clearly

    Reply

Thoughts?