PHP setcookie() path parameter and modrewrite

23 July 2010 | Posted by Richard Turner
PHP

PHP

I just thought i’d post this as it’s stumped me for a good hour and maybe someone will find it on Google later and it will save them the bother.

If the 4th parameter of setcookie() (which is path) is not set, it uses the current working directory, as per the manual.

However if you have mod-rewrite on your website that rewrites URLs to another directory (e.g. root) and you set a cookie on a page such as “/section-name/page-name”, the cookie will still only be available to either scripts in a directory named “section-name” or other rewrite URLs matching the same pattern e.g. “/section-name/page-two”. It will not be available to other scripts in the root directory, this even includes the one that originally set the cookie if it’s called via another mod-rewrite rule that doesn’t match “/section-name/xxx”.

Therefore setcookie uses the REQUEST_URI not the actual directory of the script that’s executing.

To get around this simply set the path parameter to “/” and it will be available to all scripts and directories in your website.

e.g.

setcookie(“cookie_name”, “cookie_value”, time()+60*60*24, “/”);

I hope this helps someone.

Richard Turner

Category: Uncategorized |
Enjoyed this article?

One Response so far | Have Your Say!

  1. Yolanda
    June 5th, 2011 at 6:09 pm #

    Just what I was looking for, thanks.

Leave a Feedback

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>