Detecting if the cookies are enabled with PHP

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 🙂

6 thoughts on “Detecting if the cookies are enabled with PHP

  1. Nik ChankovNo Gravatar Post author

    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.

  2. viliam22No Gravatar

    Hi,
    I was tried use some like this when dont want to refresh page:
    <?php
    // is_cookie_enable (?)
    session_start();
    $_SESSION['cas'] = time();
    $prem = SID;
    if ( !empty($prem) )
    echo "Cookie is enable”;
    echo $prem;
    ?>
    What you saying on this ? I dont know Is it right ? When I test it work.

  3. mesamorphoNo Gravatar

    This may fail if the user bookmarks the page with ?cookies=true and returns in another browser session (by which time the cookie created during the first iteration of the above script would have been deleted), and/or if they changed their browser’s cookie setting (to accept cookies) since the last time they requested the page. A workaround would be to pass a time value query string along with/or instead of cookies=true and revise the script such that it would restart with the first iteration (set cookie, reload & check if cookie exists) if too much time passed between now and the time identified via said additional query string.

    All that said, by far the most efficient method to check the browser’s cookie setting is to use JavaScript.

  4. JosehNo Gravatar

    the best solution would be as soon as someone visit you site set a cookie and then where you need the cookies enabled you check to see if the cookie exist

  5. Pingback: Check if cookies are enabled - PHP Solution - Developers Q & A

Leave a Reply

Your email address will not be published. Required fields are marked *