【问题标题】:PHP Session or Cookie after Refreshing a Page刷新页面后的 PHP 会话或 Cookie
【发布时间】:2016-06-27 03:27:11
【问题描述】:

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

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

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


$forAnimation;

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

【问题讨论】:

  • 对不起,我已经更新了我尝试使用 cookie 的代码 sn-p。
  • 如手册 (php.net/manual/en/function.setcookie.php) 中所示,setcookie 上应该有一个键和值。 $forAnimation = true; setcookie("pollChart",$forAnimation); 现在您应该将 $_COOKIE['pollChart'] 设置为 true
  • 第一次加载和页面刷新后仍然返回相同的值。

标签: php session cookies refresh


【解决方案1】:

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
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 2019-04-28
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    相关资源
    最近更新 更多