2012-04-05 98 views
1

我想检查我的网站用户是否允许Cookie。检测客户端的浏览器是否已关闭Cookie

基本上我要做到以下几点:

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

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

+1

入住这http://stackoverflow.com/questions/531393/how-to-detect-if-cookies-are-disabled-is-it-possible – 2012-04-05 13:26:15

回答

1

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

+0

我怎么能知道它的下一个请求是来自其他用户的新请求还是禁用了Cookie的用户? – 2012-04-05 13:41:15

+0

就像登录这样的情况将是可能的。 – julesj 2012-04-05 18:26:19

4

如上:它不会总是有效。

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

<?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'); 
    } 
} 
?> 
+0

+1今天加入并给出有效答案 – Baba 2012-04-05 14:56:07

-2

要准确地回答你的问题,如果你在你的代码中创建一个功能

<?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或$ 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> 
+0

此解决方案不适用于第一个HTTP请求。只有在页面重新加载(并发送第二个)之后。 – automatix 2014-11-11 13:49:05

+0

@automatix你说的没错。我改变了我的答案以添加重定向,我现在意识到我的答案基本上与Anhonime相同 – icc97 2014-11-12 22:41:52

相关问题