PHP Session in iFrame in Safari and other browsers.

May 27, 2014

Problem:  session does not get created in the iframe from another domain. Solution is below.

Solution for most browsers will be placing following line right before you start your session
header('P3P: CP="CAO PSA OUR"');
session_start();
 
This will allow you create session in iFrame in most browsers. (what is it can be found here: http://www.w3.org/P3P/)
After placing this most browsers will work, but Safari will not. Here is another workaround for safari: (iFrame source www.domain.com placed on the www.otherDomain.com)
 
1. On load of iFrame check if we are using safari and session is not created, and if so ->
2. Redirect parent window to the www.domain.com, create session there
3. Redirect back to the www.otherDomain.com where iFrame is used.
 
Here is code that you need to place:
 
IFrame code:
 
<?php
header
('P3P: CP="CAO PSA OUR"');
session_start();

// Check if safari
// Check if not chrome, because chrome outputs Safari*
// Check if no cookie/session is set
if (strpos($_SERVER["HTTP_USER_AGENT"], "Safari")
    && !strpos($_SERVER["HTTP_USER_AGENT"], "Chrome")) {
    if (
count($_COOKIE) === 0) {
     echo 
"<script> 
     top.location = 'http://domain.com/setSession.php';
     </script>"
;
     exit(); 
// need to be there in order not to load the rest of the page
    }
}
?>
 
setSession.php code:
 
<?php
header('P3P: CP="CAO PSA OUR"');
session_start();
$_SESSION = array(); 
// set session
 
echo 
"<script> top.location = '
http://otherDomain.com'; </script>";
?>
 
* HTTP_USER_AGENT output of Chrome: 
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36