Приглашаем посетить
Чарушин (charushin.lit-info.ru)

Checking Whether the Client Supports Cookies

Previous
Table of Contents
Next

Checking Whether the Client Supports Cookies

$test_temp = isset($_COOKIE['test_temp']) ?
     'supports' : 'does not support';
$test_persist = isset($_COOKIE['test_persist']) ?
     'supports' : 'does not support';


Remember the way cookies are sent: First, the server sends the cookie to the client as part of the HTTP response. In the next request, the client sends the cookie back if accepted. Therefore, calling setcookie() and then checking the contents of $_COOKIE does not work. You have to wait for the next HTTP request.

Testing the Cookie Configuration of a Browser (cookietest.php)
<?php
  if (isset($_GET['step']) && $_GET['step'] == '2')
   {
    $test_temp = isset($_COOKIE['test_temp']) ?
      'supports' : 'does not support';
    $test_persist = isset($_COOKIE['test_persist'])
      ?
      'supports' : 'does not support';
    setcookie('test_temp', '', time() -
      365*24*60*60);
    setcookie('test_persist', '', time() -
      365*24*60*60);
    echo "Browser $test_temp temporary cookies.<br
       />";
    echo "Browser $test_persist persistent cookies.";
  } else {
    setcookie('test_temp', 'ok');
    setcookie('test_persist', 'ok', time() +
      14*24*60*60);
    header("Location:
      {$_SERVER['PHP_SELF']}?step=2");
  }
?>

You can, however, use header() to force the client to create a second request. In the first request, you set the cookie; in the second request, you check whether that worked.

In the previous code, two cookies are set, one temporary cookie and one persistent cookiebecause it is possible to configure some browsers so that one kind of cookie is accepted, the other one is not. Then, the redirect is done using header() and the Location: HTTP header, and the presence of the cookie(s) is checked.

Of course you should configure your browser to show a message window when a cookie arrives; that makes debugging much easier.


Previous
Table of Contents
Next