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?
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.
Use the isset() function upon the superglobal $_COOKIE variable to check if a cookie is set.
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[' ...
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.
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.
setcookie("CookieName", "value", time()+3600, "/", ".mydomain.com");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With