Categories
PHP

Check If Cookies are Allowed or Blocked

This code snippet demonstrates how to test if the cookies are enabled on the client or not.

When you create a cookie, 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.

Example: Testing whether the cookie was created on the client side:

<?php
 $step = $_GET['step'] ?? '';
 if ($step == '2') {
  $test = isset($_COOKIE['test']) ? 'YES' : 'NO';
  setcookie('test', '', 1); // delete cookie
  echo "Cookies blocked: $test";
 } else {
  setcookie('test', 'ok', time() + 14*86400);
  header("Location: {$_SERVER['PHP_SELF']}?step=2");
 }
 //Prints: Cookies blocked: NO

We used the header() function 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, we set a cookie test, then, the redirect is done using header() and the Location: HTTP header, and the presence of the cookie is checked.


Cookies and Sessions: