PHP Sessions

From Facebook Developers Wiki

Jump to: navigation, search

[edit] Method 1

The problem is that sessions in php default to using a cookie to store the session ID, but cookies are not possible in FBML. To remedy this, the API session_key is used as the php session ID:

   session_id($facebook->api_client->session_key);
   session_start();

This is confirmed working, using require_login() beforehand.

[edit] Method 2

Some people have had problems with PHP sessions being persistent. As far as I know it is impossible to store the PHPSESSID in a cookie using FBML. So, you can take $_GET['PHPSESSID'] and set it equal to the Facebook session_key before calling session_start().

The current user's UID, and the Facebook session_key are passed in one of two ways to your script.

  • If your script is loaded as FBML OR the first time you script is loaded within an iframe $_REQUEST['fb_sig_user'] and $_REQUEST['fb_sig_session_key'] will be set.
  • If you click on a link within an iframe, and load another regular page within the same iframe, then $_REQUEST['api_key_user'] and $_REQUEST['api_key_session_key'] are set, where $API_KEY is set to your unique API key.

The following code creates or retrieves a session based on the users facebook session_key then seeds it with the fb parameters from the request.

 $API_KEY = '...';

 $prefix = ($_REQUEST['fb_sig_user']) ? 'fb_sig' : $API_KEY;

 if( isset($_REQUEST[$prefix.'_session_key']) ){
    session_name( $_REQUEST[$prefix.'_session_key'] );
    session_start();

    $_SESSION['fb_user']        = $_REQUEST[$prefix.'_user'];
    $_SESSION['fb_session_key'] = $_REQUEST[$prefix.'_session_key'];
    $_SESSION['fb_expires']     = $_REQUEST[$prefix.'_expires'];
    $_SESSION['fb_in_canvas']   = $_REQUEST[$prefix.'_in_canvas'];
    $_SESSION['fb_time']        = $_REQUEST[$prefix.'_time'];
    $_SESSION['fb_profile_update_time'] = $_REQUEST[$prefix.'_profile_update_time'];
    $_SESSION['fb_api_key']     = $_REQUEST[$prefix.'_api_key'];
 } else {
    // Just so there *is* a session for times when there is no fb session
    session_start();
 }