Facebook Safari Session Problem – Safari Iframe Set Cookie

If you’re struggling with a session_start or cookie in safari you may already know that Apple decided to enforce the cookie policy and fix some security issues that allowed us to add cookies from third party websites – for instance iframes such as Facebook Apps & Page tabs.

I have created a workaround for this, since basically all you need to do is load your page on top.location, create the session and redirect it back to facebook.

Add this code in the top of your index.php and set $page_url to your application final tab/app URL and you’ll see your application will work without any problem.

  1. <?php
  2.         // Start Session Fix
  3.         session_start();
  4.         $page_url = "http://www.facebook.com/pages/…/…?sk=app_…";
  5.         if (isset($_GET["start_session"]))
  6.             die(header("Location:" . $page_url));
  7.         $sid = session_id();
  8.         if (!isset($_GET["sid"]))
  9.         {
  10.             if(isset($_POST["signed_request"]))
  11.                $_SESSION["signed_request"] = $_POST["signed_request"];
  12.             die(header("Location:?sid=" . $sid));
  13.         }
  14.         if (empty($sid) || $_GET["sid"] != $sid)
  15.             die(‘<script>top.window.location="?start_session=true";</script>’);
  16.         // End Session Fix
  17. ?>
Open Source Junior Developer
Posted on by Diogo Raminhos This entry was posted in News & Updates, PHP. Bookmark the permalink.

7 Responses to “Facebook Safari Session Problem – Safari Iframe Set Cookie”

  1. Leandro Gomes says:

    Thanks for the solution. It works nice :D

  2. Ricardo says:

    Thanks for the solution, it’s solves the problem with Safari but it seems to kill the session since my POST calls stop working after implementing this. Any idea why?

    • Hello @Ricardo,
      Just updated the code snipped, you just need to add any $_REQUEST/$_POST/$_GET variables (such as signed_request, as shown above) to session and use them (the session variables) instead.
      Thank you and sorry for the late reply!

  3. Eugenio says:

    You just save my life.
    Thanks!

  4. This is just throwing me into an infinite loop of redirects. Does this code need to be on every page, like in the config file, or just on the index page?

Leave a Reply