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!