PHP Checking to See If a Users Browser Accepts Cookies

Dec 06, 2009 Author: dev99

To see if a browser accepts cookies, you must check in two distinct steps, in two distinct web requests. The client's browser must make two requests because the browser sets a cookie only when it gets a response from the first request.

You can serve both requests with one script, but you have to be careful not to put the browser in an infinite loop. The idea is to check for the cookie, and if the cookie is not set, you must try to set it and reload the page. But you want to reload only once, so you also have to tell the script that it is doing a reload to prevent it from loading yet again if the cookie is not set.

This is a small script, but because you run the risk of infinitely reloading pages, you have to be careful. The first thing we do is check to see if the cookie we're testing is already set. If so, since the browser supports cookies, there's nothing left to do:

<?php
if (isset($_COOKIE["test"])) {
    print "Cookies enabled.";

If this cookie does not exist, then there are two possible situations: First, the browser may not accept cookies. However, we won't know for sure until the second time we load the page, and we need to know when the browser has reloaded the page. To achieve this, we'll set a GET parameter called testing on the second access. If this parameter exists and the cookie doesn't exist, then we know that the browser isn't sending cookies:

 else {
    if (isset($_REQUEST["testing"])) {
        print "Cookies disabled.";

However, if the cookie doesn't exist and the testing parameter does not exist, then this is the first time that the browser has accessed the page. Therefore, we want to set the cookie and then reload the page, this time setting the testing parameter to indicate that it's a second access. You'll see how the Location header works in the following section.

  
  } else {
        setcookie("test", "1", 0, "/");
        header("Location: $_SERVER[PHP_SELF]?testing=1");
    }
}

It's extremely important that you do not forget to include the testing parameter. If you omit it, the page will reload infinitely if the browser does not support cookies.This script isn't terribly intuitive to read, because the first pieces that the user encounters do not correspond to the first lines of code. However, it is so small that you can easily understand it entirely, and once you do that, you should have no problems with it.


views 7179
  1. Add New Comment

gravatar
Mike
March 6,2011 at 16:28:43
Excellent, works well thanks!