Page 1 of 1
Get if cookies are enabled?
Posted: Wed Feb 25, 2009 8:19 am
by Sindarin
I want to display an error message if cookies are disabled.
I set a test cookie to find out if they are enabled or not
Code: Select all
<?php
setcookie('test',1);
if ($_COOKIE['test']==1)
{
echo "cookie is set";
}
else
{
echo "cookie is not set";
}
?>
However the very first time the page is accessed, the $_COOKIE['test'] returns nothing, but when I refresh the page it returns 1, resulting in a false "You don't have cookies enabled" message at the start. It seems php has problems getting the cookie value right after it sets it. Is there a way to fix this?
Re: Get if cookies are enabled?
Posted: Wed Feb 25, 2009 8:35 am
by mattpointblank
When you set a cookie, you have to reload the page to make it take effect. Use a header() redirect after setting it, to the same page, effectively refreshing it.
Re: Get if cookies are enabled?
Posted: Wed Feb 25, 2009 8:46 am
by Sindarin
Code: Select all
<?php
ob_start();
if ($_COOKIE['test']=='')
{
setcookie('test',1);
header('Location:cookie.php');
}
if ($_COOKIE['test']==1)
{
echo "cookie is set";
}
else
{
echo "cookie is not set";
}
ob_end_flush();
?>
If the user has cookies disabled, Firefox outputs:
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

Re: Get if cookies are enabled?
Posted: Wed Feb 25, 2009 8:57 am
by mattpointblank
Yep, because of your logic. If the user enters your page with cookies disabled, it will detect there's no cookie, and redirect them / refresh the page. Then it will detect they have no cookie, and refresh the page... etc. Maybe put the cookie setting code on one page then redirect to another?
Re: Get if cookies are enabled?
Posted: Wed Feb 25, 2009 9:18 am
by VladSun
or use:
Code: Select all
header('Location:cookie.php?cookie_check=done');
and check $_GET['cookie_check']
Also, always put a call to exit() after header() is called