Detect if cookies are enabled in PHP

I think its better to make one file set cookie and redirect to another file. Then the next file can check the value and determine if cookie is enabled. See the example.

Create two files, cookiechecker.php and stat.php

// cookiechecker.php
// save the referrer in session. if cookie works we can get back to it later.
session_start();
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// setting cookie to test
setcookie('foo', 'bar', time()+3600);
header("location: stat.php");

and

stat.php

<?php if(isset($_COOKIE['foo']) && $_COOKIE['foo']=='bar'): 
// cookie is working
session_start();
// get back to our old page
header("location: {$_SESSION['page']}");
else:            // show the message ?>
cookie is not working
<? endif; ?>

Load cookiechecker.php in browser it’ll tell cookie is working. Call it with command line like curl. It’ll say, cookie is not working


Update

Here is a single file solution.

session_start();

if (isset($_GET['check']) && $_GET['check'] == true) {
    if (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
        // cookie is working
        // get back to our old page
        header("location: {$_SESSION['page']}");
    } else {
        // show the message "cookie is not working"
    }
} else {
    // save the referrer in session. if cookie works we can get back to it later.
    $_SESSION['page'] = $_SERVER['HTTP_REFERER'];
   // set a cookie to test
    setcookie('foo', 'bar', time() + 3600);
    // redirecting to the same page to check 
    header("location: {$_SERVER['PHP_SELF']}?check=true");
}

Leave a Comment