Get if cookies are enabled?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Get if cookies are enabled?

Post 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?
mattpointblank
Forum Contributor
Posts: 304
Joined: Tue Dec 23, 2008 6:29 am

Re: Get if cookies are enabled?

Post 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.
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Re: Get if cookies are enabled?

Post 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.
:(
mattpointblank
Forum Contributor
Posts: 304
Joined: Tue Dec 23, 2008 6:29 am

Re: Get if cookies are enabled?

Post 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?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Get if cookies are enabled?

Post 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
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply