302 redirects and cookies
Date: 25 Nov 2012Author: Erik Dubbelboer
When working on a project I was wondering if all browsers would accept cookies set in http redirects. After searching for a bit I found some contradicting articles and bug reports indicating that this might not always be the case. So I decided to test this in a lot of browsers and post the results online for others to find.
I wrote a small test page: dubbelboer.com/302cookie.php
What I found is that all major browsers, IE (6, 7, 8, 9, 10), FF (17), Safari (6.0.2), Opera (12.11) on both windows and Mac, set cookies on redirects. This is true for both 301 and 302 redirects. But keep in mind that 301 responses are cached much more aggressively most by browsers.
302cookie.php
<?
if (isset($_GET['show'])) {
// Delete the cookie (note: it will still be set in $_COOKIE).
setcookie('test');
echo 'Cookie was: ';
if (isset($_COOKIE['test']) && ($_COOKIE['test'] == $_GET['show'])) {
echo 'SET';
} else {
echo 'NOT SET';
}
// Make sure this is a new url. This is needed for 301 responses which are otherwise cached.
echo '<br><a href="?a=' , microtime(true) , '">try again</a>';
} else {
$id = microtime(true);
setcookie('test', $id, time() + 4);
header('Location: ?show=' . $id, true, 302); // Could also use 301.
}