00 Votes

Cookie only works on certain areas of my website

Question by SmartUser | 2012-03-25 at 10:14

I really do not know what it could be! For a new project I am using the following code to set a cookie:

setcookie('cookiename', 'value', time()+3600);

The same code, I have already tried in an old project and there were never any problems. Now, however, almost nothing is working! Sometimes, this code works and the cookie is available, sometimes it seems as if the browser simply cannot find the cookie at all!

The error is not in the PHP code above, isn't it? Does anyone know what this might be?

ReplyPositiveNegative
1Best Answer1 Vote

Of course, I can now only make a guess what it could be. But try it once with the following code:

setcookie('name','value',time()+3600,'/','.example.com');

This has the following background: By default, the cookie is available in the directory in which it was also created. If you create a cookie, for example, in the directory example.com/directory, it is only available there, but not directly under example.com or under example.com/otherdirectory.

If this also applies to you, you can see, for example, in your browser, if you look at the properties of the cookie. So that the cookie is available on the entire page, here should stand '/' and not '/directory'. And that is what we do with the fourth parameter in the setcookie() function above.

Under certain circumstances, you will also need the fifth parameter. Enter here your domain and do not forget the point at the beginning of it. This ensures that the cookie is also known under subdomains such as de.example.com and not just under www.example.com. This could also be a reason, why your browser cannot find the cookie.

Presumably, in your other project, you have not set the cookie in a subdirectory or you have not used subdomains or subdirectories in your whole project at all. And without them, it should also work in the way, you have used above.
2012-03-25 at 16:13

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.