随着时间设置cookie

时间:2015-01-16 02:59:34

标签: php time setcookie

需要检查cookie以查看时间是否小于当前时间减去一小时。但是我目前的模型不起作用。基本上,这将在一定时间间隔内对cookie进行几次测试,然后再将cookie全部删除。

    <?php

        if (isset($_COOKIE['cookieTest'])) {
            if ($_COOKIE['cookieTest'] < (time() - (60*60))) {
                $content = '<h2 style="color:green;font-weight:bold;">Cookie set a minute again.</h2>';
                unset($_COOKIE['cookieTest']);
            } else {
                $content = '<h3 style="color:red;">Hasn\'t been a minute!</h3>';
            }
        } else {

            setcookie('cookieTest',
                        time(), 
                        (time()+3600), 
                        '/', 
                        'bfxsocial.strangled.net'
                    ) or die('<!DOCTYPE html>
                                <html lang="en">
                                    <head>
                                        <title>Test Cookie</title>
                                    </head>
                                    <body>
                                        <h3 style="color:red;">Cookie failed to be set</h3>
                                    </body>
                            </html>');

            $content = '<h3 style="color:orange;">Cookie just set</h3>';

        }
    ?>
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>Test Cookie</title>
        </head>
        <body>
            <?php echo $content; ?>
        </body>
    </html>

1 个答案:

答案 0 :(得分:0)

我不确定最终目标是什么或者你想要完成什么,但也许这会有所帮助:

<?php

date_default_timezone_set('America/Chicago');

$time = $_COOKIE['cookieTest']; // Timestamp to test
$t = '1 hour'; // Length in the past

if($time < strtotime("- $t"))
{
    //Timestamp is older than $t.
}
else
{
    //Timestamp is NOT older than $t.
}