Sessions are not working when the site is called by an iframe

Viewed 7271

I have a first site https://www.mydomain1.com in which I use PHP sessions. No problem, everything works fine, when I go from page to page, I can access my session variables.

I have a second site https://www.mydomain1.com in which I display part of my 1st site via an iframe:

<iframe src = "https://www.mydomain1.com" width = "100%" frameborder = "0" style = "border: 0" allowfullscreen = "allowfullscreen" id = "frameLeonard"> </iframe>

And there strangely, the session variables are no longer recognized. I'm not even trying to get my 1st site to access the session variables from the 2nd site (that's not the goal and it's normal that it doesn't work) but just run the 2nd site inside the 1st site.

Strangely, it was still working a year ago. Has there been any upgrade that would explain the problem?

Thank you in advance for your lights !

3 Answers

Now I found the reason, chrome shows this behaviour. With version 80 (Feb. 2020) it has it's "SameSite by default cookies" enabled as default, which means that including external pages (different domain) inside an iframe, will kill their sessions.

For preventing this, you can disable "SameSite by default cookies" in chrome://flags Beware: This might be a security issue (but solved my problem for now)

Otherwise - if using PHP 7.3 or newer - you could add one (or both) of the following ini_set() in your PHP before session_start():

ini_set('session.cookie_samesite', 'None');
session_set_cookie_params(['samesite' => 'None']);

Here you get further details: https://blog.heroku.com/chrome-changes-samesite-cookie#prepare-for-chrome-80-updates

Having the same problem here, but no solution yet. I made several tests. Seems only to occur, when iFrame loaded content is SSL certificated. If not, it works perfect. Maybe this is helpful. Or did you get any solution yet?

i recommend you use MySQL function for that,

// to add captcha record via img file.

$time = time();
$deltime = time()-1500;
$ip = $_SERVER['REMOTE_ADDR'];

    $result = $conn->query("SELECT * FROM `captcha` WHERE `ip` = '" . $ip . "'");
    if (($result) && ($result->num_rows >= 1))
    { 
        $conn->query("UPDATE `captcha` SET `captcha` = '".$_SESSION["captcha"]."' WHERE `ip` = '".$ip."'");
  }
  else 
  {
      
$conn->query("DELETE FROM `captcha` WHERE `time` < '".$deltime."'");
      
$sql = "INSERT INTO `captcha` (captcha, ip, time) VALUES ('".$_SESSION["captcha"]."', '".$ip."', '".$time."')";

if ($conn->query($sql) === TRUE) {
  //echo "New record created successfully";
} else {
  //echo "Error: " . $sql . "<br>" . $conn->error;
}
  }

// on process file to match captcha code

$ip = $_SERVER['REMOTE_ADDR'];
$result = $conn->query("SELECT * FROM `captcha` WHERE `ip` = '" . $ip . "'");
while ($row = $result->fetch_assoc())
{ 
     $captcha = $row['captcha'];
}
if ($captcha == $_POST["access_token"]) { /* do anything */ }
Related