Kyle
Kyle

Reputation: 21

I'm setting a cookie in PHP but it's not being sent with the headers

Greetings.

I'm attempting to save a user's session id in the browser cookies. I have tested over and over and I'm not having any problems with whitespace or any other information being sent before the headers.

My application has one entry point (index.php) and processes the query string to call controllers/etc. When I go to my main page, no cookies are visible, so it shows the user login page. When I trace through this with XDebug, once I hit submit, which POSTs back to index.php. When this POSTs back, the cookies from previous logins are sent to the page! However, since it's trying to process the POST information, my script sets the cookie again. When it redirects back to the main page (i.e. index.php with no POST or other parameters) the cookies aren't sent.

I've debugged and looked through this all over the place and can't figure it out, wondering if anyone has any bright ideas.

NOTE: I am setting the path to '/' in the setcookie(). Also, I am using mod_rewrite and an .htaccess to make SEO-friendly URLs. However, I've tried without it and it doesn't seem to matter...

Code Snippets:

To write:

setcookie(self::SESSION_COOKIE, $this->session_id, time()+60*60*24*30, '/', 'localhost');

To access:

$_COOKIE[self::SESSION_COOKIE];

Thanks for the help -

Upvotes: 2

Views: 823

Answers (1)

webbiedave
webbiedave

Reputation: 48897

Check the path parameter that you are passing to the setcookie function. Ensure it is set to '/' (or whatever your application's URI root is).

From the manual:

path

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

Upvotes: 1

Related Questions