正在检测客户端';的浏览器已关闭Cookie


Detecting if client's browser has Cookies Turned Off

我想检查我的网站用户是否允许cookie。

基本上我想做以下事情:

<?php
     if(cookies are enabled)
     {
          /* Cookies related code goes here */
          /* Create PHP cookie, read cookies etc */
     }
     else
     {
          /* Do something else */
     }
?>

我的想法是检查setcookie函数是否返回true,然后启用cookie,否则不启用。

如上所述:它并不总是有效的。

所以,基本上,你可以这样做:

<?php
setcookie('enabled', '1');
if($_COOKIE['enabled']=='1'){
    echo('Cookies are enabled. ');
}else{
    if($_GET['nocookies']==1){
        echo('Cookies are disabled. ');
    }else{
        $adr = explode('/', $_SERVER['SCRIPT_NAME']);
        header('Location: '.$adr[count($adr)-1].'?nocookies=1');
    }
}
?>

返回"setcookie"是不够的。在Firefox的情况下,即使禁用了cookie,该函数也会返回true。我认为最好的检查方法是在cookie中设置一个值,并在下一个请求中检查该值。

要准确回答您的问题,如果您创建了一个函数

<?php
function cookies_are_enabled() {
    setcookie('enabled', 'enabled');
    return $_COOKIE['enabled'] === 'enabled';
}
?>

然后在你的代码中你有:

<?php
if (cookies_are_enabled()) {
  /* Cookies related code goes here */
  /* Create PHP cookie, read cookies etc */
} else {
  /* Do something else */
}
?>

更新:如评论中所述。这不会直接起作用。来自setcookie PHP页面(我强调):

'一旦设置了COOKIE,就可以在下一页加载时使用$_COOKIE或$HTTP_COOKIE_VARS数组访问它们。注意,像$_COOKIE这样的超全局变量在PHP 4.1.0中已经可用。Cookie值也存在于$_REQUEST中

考虑到您不能信任setcookie,我能想到的最好的办法就是强制重定向。

<?php
function cookies_are_enabled() {
    // if first page load
    // set cookie and redirect
    // if redirected check the cookie
    if (isset($_GET['cookie_check'])) {
        return $_COOKIE['enabled'] === 'enabled';
    } else {
        setcookie('enabled', 'enabled');
        if (empty($_SERVER['QUERY_STRING'])) {
            $url = $_SERVER['PHP_SELF'].'?cookie_check=1';
        } else {
            $url = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&cookie_check=1';
        }
        exit(header("Location: $url"));
    }
}
if (cookies_are_enabled()) {
    /* Cookies related code goes here */
    /* Create PHP cookie, read cookies etc */
    $message = 'cookies are enabled';
} else {
    /* Do something else */
    $message = 'cookies are <strong>not</strong> enabled';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cookies!</title>
</head>
<body>
    <p><?php echo $message; ?></p>
</body>
</html>