Search code examples
phpwordpresscookiessession-cookies

Cookie array with strings returns 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), "/");
?>

Solution

  • 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), "/");