dongzhui9936 2019-06-21 22:07
浏览 306
已采纳

带有字符串的Cookie数组返回false

I'm trying to add the current page's URL to a cookie called '$visitedPages'. For reference, the Wordpress function 'get_permalink()' returns the URL.

In the below, the var_dump returns 'false'. Whereas if I replace 'get_permalink()' on line 2 with 'get_the_ID()', which returns the integer page IDs, this all works just fine.

I tried stripping special characters from the url, but it still returns 'false', so I suspect this problem is something to do with decoding strings from the 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), "/");
?>
  • 写回答

2条回答 默认 最新

  • douke8473 2019-06-23 11:31
    关注

    I needed to remove escaped quotes from the cookie with stripslashes() before the json_decode. Why json_decode doesn't do this itself, I have no idea.

    Here is the working code. Note: it is better to use exactly the same code but with json_encode() and json_decode() instead of serialize() and unserialize() so I've changed that too, but the principle is the same.

    // 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), "/");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗