Check if cookies are enabled

JavaScript

In JavaScript you simple test for the cookieEnabled property, which is supported in all major browsers. If you deal with an older browser, you can set a cookie and check if it exists. (borrowed from Modernizer):

if (navigator.cookieEnabled) return true;

// set and read cookie
document.cookie = "cookietest=1";
var ret = document.cookie.indexOf("cookietest=") != -1;

// delete cookie
document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";

return ret;

PHP

In PHP it is rather “complicated” since you have to refresh the page or redirect to another script. Here I will use two scripts:

somescript.php

<?php
session_start();
setcookie('foo', 'bar', time()+3600);
header("location: check.php");

check.php

<?php echo (isset($_COOKIE['foo']) && $_COOKIE['foo']=='bar') ? 'enabled' : 'disabled';

Leave a Comment