Fire
Fire

Reputation: 31

the cookie disappear when I change page

(PHP) I set the cookie in my login.php page in this way:

setcookie('cookie_id',$id);

I print the cookie and I see the correct value but when I change page with:

header($login_url);

I lose the all cookie and I don't know why. Anybody can help me?

Upvotes: 3

Views: 4572

Answers (2)

Ninju
Ninju

Reputation: 2530

If you have human urls or subfolders (like www.domain.com/path1/path2/), then you must set cookie path to / to work for all paths, not just current one.

setcookie('cookie_id', $cookie_id, time() + 60*60*24*30, '/');

From PHP manual:

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

marian0
marian0

Reputation: 3327

You have to specify / as path in setcookie() function, so cookie will be available on every path of your site. To do this:

setcookie('cookie_id', $id, 0, '/');

Note that third argument is expire time which is set to 0 as default. According to documentation it means that:

If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).

Upvotes: 3

Related Questions