Cookie检测代码无效

时间:2015-12-11 03:56:59

标签: php cookies

好的,我正在建立一个会员区部分,我需要检查浏览器是否支持cookie。索引页面将检查cookie是否存在,如果不存在,将设置一个cookie并重定向到另一个页面,该页面将检查设置cookie并重定向回索引页面,如果它找到cookie,否则将显示一条错误消息询问用户启用cookie。请帮助我收到“No cookie”消息。

的index.php

<?php
    if( !isset($_COOKIE['cookies_enabled']) ){
    setcookie( 'cookies_enabled', '', time() + 3600 * 24 * 365, '', '.example.com', 0, 1 );
    header("Location: http://www.example.com/members/login.php");
    exit;       
}else{
    $cookie_enabled = TRUE;
}
?>

<?php if( $cookie_enabled ) : ?>
    //do stuff
<?php endif; ?>

的login.php

<?php
    if( isset($_COOKIE['cookies_enabled']) ){
    header("Location: http://www.example.com/members/");
    exit;
}else{
    $cookie_enabled = FALSE;
}
?>

<?php if( $cookie_enabled === FALSE ): ?>

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    </head>

    <body>

        <p>No cookie</p>

    </body>
    </html>

<?php endif; ?>

1 个答案:

答案 0 :(得分:0)

设置cookie值时出现小错误。

setcookie( 'cookies_enabled', 'COOKIE_VALUE', time() + 3600 * 24 * 365, '', '.example.com', 0, 1 );

由于您正在检查cookie是否已设置,因此您需要指定cookie值(我在代码中将其设置为COOKIE_VALUE)。为cookie添加适当的值,然后它应该可以工作。

我希望这会有所帮助。

相关问题