Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP cookie problem - www or without www

Why is it that if I create a cookie on www.example.com and check it on example.com, the cookie doesn't exist there? I am planning to just use .htaccess redirect non-www to a www domain. But how do I solve this?

like image 806
Loreto Gabawa Jr. Avatar asked Feb 26 '10 22:02

Loreto Gabawa Jr.


People also ask

How does PHP handle HTTP cookies?

Accessing Cookies with PHP Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example. You can use isset() function to check if a cookie is set or not.

What PHP function checks if a cookie exists or not?

Use the isset() function upon the superglobal $_COOKIE variable to check if a cookie is set.

How set multiple values in cookie in PHP?

php'; function setCookieData($arr) { $cookiedata = getAllCookieData(); if ($cookiedata == null) { $cookiedata = array(); } foreach ($arr as $name => $value) { $cookiedata[$name] = $value; } setcookie('cookiedata', serialize($cookiedata), time() + 30*24*60*60); } function getAllCookieData() { if (isset($_COOKIE[' ...

Can we destroy cookies in PHP?

Deleting Cookie: There is no special dedicated function provided in PHP to delete a cookie. All we have to do is to update the expire-time value of the cookie by setting it to a past time using the setcookie() function.


2 Answers

Browsers are the main culprit here, not PHP. They store by domain, and don't know that www is a special case; from their perspective, www.mydomain.com and mydomain.com are different strings, and therefore have different security policies. However, there is something you can do.

When setting the cookie, use .mydomain.com (with the leading dot). This will tell your user's browser make the cookie accessible to mydomain.com and all subdomains, including www. PHP's setcookie has the argument $domain, but it's fifth on the list, so you may need to set $expire and $path to their default values in order to get at it.

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

For consistency, however, you may wish to consider rerouting all web traffic to a specific domain, i.e. send mydomain.com traffic to www.mydomain.com, or vice-versa. My vague knowledge of SEO (edit if incorrect) tells me that it's helpful so as not to have duplicate content, and it saves you all such authentication issues. Additionally, if you store assets on a subdomain, having cookies on there slows down traffic by having to transport it each time, so storing application cookies only on www earns you that speed boost.

Here is a tutorial on how to accomplish such a redirect in Apache.

like image 199
Matchu Avatar answered Sep 21 '22 04:09

Matchu


setcookie("CookieName", "value", time()+3600, "/", ".mydomain.com");
like image 27
Can Aydoğan Avatar answered Sep 19 '22 04:09

Can Aydoğan