Detecting if the cookies are enabled with PHP

January 16th, 2010 by Nik Chankov Leave a reply »

For my current project I need a detection if the cookies are enabled or not in the user’s browser.

The easiest way to do this is by using this code:

<?php
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
    header('Location:/info.php?cookies=true');
}
if(count($_COOKIE) > 0){
    echo "Cookies are yummy!";
} else {
    echo "You didn't bring any cookies here. We are hungry!";
}
?>

The CakePHP way is almost similar:

<?php
$this->Cookie->write('test', 1);
if(!isset($_GET['cookies'])){
    header('Location:/info.php?cookies=true');
}
if(count($_COOKIE) > 0){
    echo "Cookies are yummy!";
} else {
    echo "You didn't bring any cookies here. We are hungry!";
}
?>

Ok, it’s not rocket science, but it helps :)

Advertisement

2 comments

  1. Hm, are you sure this works? From the setcookie documentation: “Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires.”

  2. Nik Chankov says:

    Daniel, you are absolutely right. That’s why I changed the code in the post.

    My mistake is that I disabled/enabled the cookies without deleting them.

    Probably I should leave this check to the JS, as it should be.

Leave a Reply