PHP SDK Demystified – Cookies Handling

I remember that there were once some discussion in the Facebook Developer Forum on topic like “why even after I logout from Facebook, I can still access my Facebook application directly w/o any login again?”.

The reason for that is because the PHP SDK has made use of cookies to store the current session and when you visit the application next time, if the cookies is not yet expired, the session will be rebuilt.

In this article, we will take a look at how cookies are being handled in the PHP SDK.

First of all, every cookie has a name and in the PHP SDK, it is set as ‘fbs_{app_ID}’ as seen in the getSessionCookieName() function.

 * The name of the Cookie that contains the session.
 * @return String the cookie name
protected function getSessionCookieName() {
  return 'fbs_' . $this->getAppId();

Below the definition of the getSessionCookieName() function is the

 * Set a JS Cookie based on the _passed in_ session. It does not use the
 * currently stored session -- you need to explicitly pass it in.
 * @param Array $session the session to use for setting the cookie
protected function setCookieFromSession($session=null) {
  if (!$this->useCookieSupport()) {
  $cookieName = $this->getSessionCookieName();
  $value = 'deleted';
  $expires = time() - 3600;
  $domain = $this->getBaseDomain();
  if ($session) {
    $value = '"' . http_build_query($session, null, '&') . '"';
    if (isset($session['base_domain'])) {
      $domain = $session['base_domain'];
    $expires = $session['expires'];

  // prepend dot if a domain is found
  if ($domain) {
    $domain = '.' . $domain;

  // if an existing cookie is not set, we dont need to delete it
  if ($value == 'deleted' && empty($_COOKIE[$cookieName])) {

  if (headers_sent()) {
    self::errorLog('Could not set cookie. Headers already sent.');

  // ignore for code coverage as we will never be able to setcookie in a CLI
  // environment
  // @codeCoverageIgnoreStart
  } else {
    setcookie($cookieName, $value, $expires, '/', $domain);
  // @codeCoverageIgnoreEnd

This function is basically used to stored the current session object $session as a cookie.

To highlight some of the keys points:

  • if “cookieSupport” is not used, this function does nothing
  • the cookies expiry time is set as 3600 seconds (i.e. 1 hour)

So, depending on your preference, you can say not to use the cookie support feature of the PHP SDK.  Or you can adjust the expiry time to what you think suitable for your application.

This entry was posted in PHP SDK Demystified and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *