Setting cookies in PHP

My experience with setting cookies with PHP, a must read for every developer that uses Windows XP and doesn’t want to spend his time debugging cookies.

If you’re using Windows XP with Internet Explorer and have a local web server running, be sure that you don’t configure the domain name when you’re setting a cookie within your PHP script. Use the value boolean(false) instead. Windows XP in combination with Internet Explorer, will not set a cookie when the domain name points to localhost. Firefox however, will successfully set your cookie.

Example:

<?php
# this
will not work in WinXP with IE, but will work in WinXP with Firefox
setcookie(‘test’, ‘value’, false, ‘/’, ‘localhost’, 0);
?>

Some say that the domain name should have a dot within it. I’ve tried that by defining a special domain name x.x in C:\Windows\System32\drivers\etc\hosts that points to 127.0.0.1 and it’s doesn’t work. I think that the problem persist that the domain name may not be pointing to 127.0.0.1 when you set a cookie.

The solution for this problem is that you don’t configure a domain name:

<?php
# this works in WinXP with IE and Firefox
setcookie(‘test’, ‘value’, false, ‘/’, false, 0);

?>

And remember:

  • Make sure that the 4th argument (path) always ends with a slash: /.
  • Make sure that the expiring time is boolean(false) or a valid timestamp that lies in the future. Zero (0) is not the value for a session cookie, it’s boolean(false).

About Sijmen Ruwhof

Independent IT Security Researcher / Ethical Hacker
This entry was posted in bug, PHP. Bookmark the permalink.