刷新页面后的PHP会话或Cookie

时间:2016-06-27 03:27:11

标签: php session cookies refresh

我是PHP的初学者,在刷新页面后,我似乎找不到有关会话或cookie的问题的答案。

我想要的是在PHP中的变量上存储一个布尔值 - 如果它是页面的第一个加载,则为true;如果不是,则为false(例如,它是刷新后的加载或类似的东西)。 / p>

你能帮我解决这个问题吗?谢谢。

$forAnimation;

if(isset($_COOKIE["pollChart"])){
    $forAnimation = false;
} else {
    setcookie("pollChart");
    $forAnimation = true;
}

1 个答案:

答案 0 :(得分:0)

Cookie非常直接,您只需设置密钥,值,到期时间等。您可以在手册中查看它的工作原理(http://php.net/manual/en/function.setcookie.php):

// If the cookie is not set
if(!isset($_COOKIE["pollChart"])){
    // Set cookie key and string value
    setcookie("pollChart",json_encode(array('set'=>false)));
// If set already, change value
} else {
    // Decode array
    $dec    =   json_decode($_COOKIE['pollChart'],true);
    // If the set value is true
    if($dec['set'])
        // Expire the cookie
        setcookie("pollChart",'',(time()-3600));
    // If set to false turn it to true
    else
        setcookie("pollChart",json_encode(array('set'=>true)));
}

// Get the contents of the cookies set
print_r($_COOKIE);

为您提供首次加载:

Array
(
    [PHPSESSID] => 4c4871ac239cec6fa2f3f43bcbed6d81
    [pollChart] => {"set":false}
)

第二次加载:

Array
(
    [PHPSESSID] => 4c4871ac239cec6fa2f3f43bcbed6d81
    [pollChart] => {"set":true}
)

上次加载:

Array
(
    [PHPSESSID] => 4c4871ac239cec6fa2f3f43bcbed6d81
)
相关问题