Spent a whole day figuring out this one. Yet another reason why Internet Explorer is the bane of web development. Found a plethora of suggested solutions on the net, and even an old bug logged for PHP in 2001, but the reason behind the bug is still a mystery.
As the title states, if you use setcookie() with $expire set and $domain not set, then IE may simply let the cookie expire, ignoring the value you put in $expire. Furthermore, IE may request the page a second time, as if it didn’t understand the cookie set directive and decided to start all over. I couldn’t reproduce this in Firefox, Chrome, Safari, or any other browser, and oddly enough, I could not reproduce this using inPrivate browsing in IE. In other words, all of the examples below work in other browsers as you would expect them to. IE is the lone failure on the setcookie example #2 below.
PHP’s setcookie() syntax:
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
1. Cookie successfully stored in IE, but expires at the end of the browser session:
setcookie(session_name(), session_id(), 0, '/');
2. The following blows away the cookie in IE:
setcookie(session_name(), session_id(), time() + 60 * 60 * 24, '/');
3. To successfully store the cookie in IE and have an expiry date, we must supply the $domain to setcookie():
setcookie(session_name(), session_id(), time() + 60 * 60 * 24, '/', '.chrislo.ca');
Some solutions on the net suggested that the time needed to be bigger in example #2 due to difference in GMT-ness of the time provided, but no matter how large the expiry time is set, the cookie still gets blown away in IE. Appending the domain magically fixed it.