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
Release: 2024-11-22 05:05:15
Original
574 people have browsed it

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
  }
}
Copy after login

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");
?>
Copy after login

check.php:

<?php
echo (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') ? 'enabled' : 'disabled';
?>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template