Web Development Blog

Check for Cookies Enabled

I recently needed to check and see if cookies were enabled for a script that I was writing for authenticating a user login. I quickly realized all the problems with this I had forgot as I don’t normally set cookies but rather normally use sessions.

Problems to overcome:

  1. Can’t check for a cookie when first setting the cookie – you have to reload the page to check for it. It would make sense to set a cookie and then in your next lines of code to check if there is a cookie, thus telling you cookies are enabled if you can pull the cookie back up. Unfortunately that will not work, you have to reload the page to check for the cookie. So this method is not a good one for what I’m doing.
  2. Don’t have to reload the browser – since about I pointed out that I have to reload a page to check for a cookie I just set I’d like to find a method were I don’t have to reload the page.
  3. No JavaScript enabled – would like to check for cookies with JavaScript. Although is not absolutely necessary for my needs so if I have to I’ll check it with JavaScript.

What I came up with:

I found several ways to check for cookies with both JavaScript and at least one way with PHP.

JavaScript:

var cookiesEnabled = (navigator.cookiesEnabled) ? true : false;

PHP:

setcookie("cookiesEnabled",1,time()+3600*24);
// Above cookie expires in 24 hours
// Next you have to reload the page to test the next part, so on first load below will give false even if cookies is enabled
$cookiesEnabled = (isset($_COOKIE['cookiesEnabled'])) ? true : fasle;

Best Method:
Below are the best methods I could come up with. I’ve create both a PHP and Javascript method. JavaScript should be cross-browser safe. Although PHP does rely on that the page being reloaded – which for a login page that should be the case.

Using JavaScript:

function isCookiesEnabled()
{
 var cookiesEnabled = (navigator.cookiesEnabled) ? true : false;
 if(typeof navigator.cookiesEnabled=="undefined" && !cookiesEnabled)
 { 
  document.cookie="testcookie";
  cookiesEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
 }
 return (cookiesEnabled);
}

Using PHP:

// Setup Cookies Enabled Check 
setcookie("cookiesEnabled",1,time()+3600*24,'/','.'.$_SERVER['SERVER_NAME']); // set for 24 hours

// Check Cookies Enabled
 $cookiesEnabled = (isset($_COOKIE['cookieEnabled'])) ? true : false;

0 Comments

Submit a Comment

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

Request A Free Quote

GET OUR PRICING GUIDE

Enter your email address below, and we'll send you our current pricing guide immediately.