Home >Backend Development >PHP Tutorial >How to Check if Cookies are Enabled with JavaScript and PHP?

How to Check if Cookies are Enabled with JavaScript and PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-22 05:05:15525browse

How to Check if Cookies are Enabled with JavaScript and PHP?

Check if Cookies are Enabled with JavaScript and PHP

JavaScript Approach:

The navigator.cookieEnabled property can determine if cookies are enabled in major browsers. However, for older browsers, a fallback approach is to set and check for a test cookie.

if (navigator.cookieEnabled) {
  // Cookies are enabled
} else {
  document.cookie = "cookietest=1";
  if (document.cookie.indexOf("cookietest=") != -1) {
    // Cookies are enabled
  } else {
    // Cookies are disabled
  }
}

PHP Approach:

In PHP, checking for cookies can be more involved. A common technique is to use two scripts: one to set a test cookie and the other to check its presence.

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';
?>

The above is the detailed content of How to Check if Cookies are Enabled with JavaScript and PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn