Internet Explorer & Safari: IFrame Session Cookie Problem

If, like me, you ever have to embed an IFrame from one domain into a website of a different domain, you will quickly realise that Internet Explorer and Safari are blocking the cookies (and thus the session variables) of the website inside the IFrame.

To reproduce the problem to its bare minimum, you would need two scripts on two different domain names (excluding localhost, as the behaviour on localhost is still different for some reason that I don’t understand).

In the sample code below, the script on domain A includes an IFrame showing the script on domain B:

Content of the script on domain A:

<iframe src="http://www.domain-B.com/embedded-script.php"></iframe>

Content of the script on domain B:

<?php
	session_start();

	echo session_id() . '<br>';
	
	if (!isset($_SESSION['count'])) {
		$_SESSION['count'] = 0;
	} else {
		$_SESSION['count']++;
	}

	echo $_SESSION['count'];
?>

If you execute the script containing the IFrame with either Internet Explorer or Safari, a new session in domain B will be created for each request, and thus the counter will never increment. All cross-domain/third-party cookies are blocked.

One workaround

If the user previously visited the website that is embedded inside the IFrame and was sent the cookie, the restrictions end.
Therefore, a script on domain A could first redirect to a script on domain B (the domain we want to embed). The script on domain B creates the session cookie, and redirects back to the script including the IFrame on domain A.

iframe ie safari workaround

Below is one possible implementation of that workaround.

Content of the script on domain A:

<?php
    if (!isset($_SESSION['isIFrameSessionStarted']))
    {
        $_SESSION['isIFrameSessionStarted'] = 1;
        $redirect = rawurlencode('http://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
        header('Location: http://www.domain-B.com/start-session.php?redirect=' . $redirect);
        exit;
    }
?>
<iframe src="http://www.domain-B.com/embedded-script.php"></iframe>

Content of the script start-session.php on domain B:

<?php
	session_start(); // create the session cookie

	$redirect = rawurldecode($_GET['redirect']);
	if (filter_var($redirect, FILTER_VALIDATE_URL) === FALSE) {
		die('Not a valid URL');
	}
	header('Location: ' . $redirect); // redirect back to domain A
	exit;
?>

This workaround only works for those who own the domain that is being embedded.
For other workarounds, read the following blog post.

Tags:
iframe Third-Party Session Cookie
iframe 3rd-Party Session Cookie
iframe Cross-Domain Session Cookie

One Reply to “Internet Explorer & Safari: IFrame Session Cookie Problem”

Post a Comment