【问题标题】:Cookie array with strings returns false带有字符串的 Cookie 数组返回 false
【发布时间】:2019-11-04 17:59:45
【问题描述】:

我正在尝试将当前页面的 URL 添加到名为“$visitedPages”的 cookie 中。作为参考,Wordpress 函数“get_permalink()”返回 URL。

在下面,var_dump 返回“假”。而如果我将第 2 行的 'get_permalink()' 替换为 'get_the_ID()',它返回整数页面 ID,这一切都很好。

我尝试从 url 中去除特殊字符,但它仍然返回 'false',所以我怀疑这个问题与从 cookie 中解码字符串有关。

// define the new value to add to the cookie
$currentPage = get_the_permalink(get_the_ID());

// if the cookie exists, read it and unserialize it. If not, create a blank array
if(isset($_COOKIE['visitedPages'])) {
    $visitedPagesSerialised = $_COOKIE['visitedPages'];
    $visitedPages = unserialize($visitedPagesSerialised)
    var_dump($visitedPages);
} else {
    $visitedPages = array();
}

// add the current page id to the array and serialize
$visitedPages[] = $currentPage;
$newCookieSerialized = serialize($visitedPages);

// save the cookie for 30 days
setcookie('visitedPages', $newCookieSerialized, time() + (86400 * 30), "/");
?>

【问题讨论】:

    标签: php wordpress cookies session-cookies


    【解决方案1】:

    尝试获取 ID,并将其添加到永久链接函数中。我假设当您说您使用 get_the_ID() 时,这意味着您正在用 get ID 函数替换永久链接函数。尝试串联使用它们。

    $page_ID = get_the_ID();
    $currentPage = get_the_permalink($page_ID);
    

    【讨论】:

    • 抱歉,打错了。我现在修改了。永久链接返回正常 - 这里的问题在于 cookie 数组。
    • 所以我明白了。您实际上是在尝试通过检查 cookie 来查看您网站上的页面是否已被访问,并查看该 URL 是否存在于 cookie 中。然后,如果尚未访问该页面,则添加它/设置 cookie。对吗?
    • 没错!如果 cookie 存储页面 ID(整数)而不是页面 URL(字符串),则代码有效,即使我去掉了符号。
    • 那为什么不直接使用页面ID呢?似乎它完成了同样的事情,并且有效:)
    • 我需要能够检测到查询字符串。仅从页面 ID 无法做到这一点:(
    【解决方案2】:

    我需要在 json_decode 之前使用 stripslashes() 从 cookie 中删除转义引号。为什么 json_decode 自己不这样做,我不知道。

    这是工作代码。注意:最好使用完全相同的代码,但使用 json_encode() 和 json_decode() 而不是 serialize() 和 unserialize() 所以我也改变了它,但原理是一样的。

    // define the new value to add to the cookie
    $currentPage = get_the_permalink(get_the_ID());
    
    // if the cookie exists, read it and unserialize it. If not, create a blank array
    if(isset($_COOKIE['visitedPages'])) {
        $visitedPagesSerialised = stripslashes($_COOKIE['visitedPages']);
        $visitedPages = json_decode($visitedPagesSerialised)
        var_dump($visitedPages);
    } else {
        $visitedPages = array();
    }
    
    // add the current page id to the array and serialize
    $visitedPages[] = $currentPage;
    $newCookieSerialized = json_encode($visitedPages);
    
    // save the cookie for 30 days
    setcookie('visitedPages', $newCookieSerialized, time() + (86400 * 30), "/");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-26
      • 2011-12-04
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多