如何在cookie中存储最后访问的n个页面


How to store last visited n pages in cookie in PHP

我搜索了1-2个小时关于在PHP cookie中存储最后访问的页面。但通常有JS的例子。你能给我举一个完整的例子吗?或者你能举一个例子吗?

我是PHP新手,我想做一些例子。

这个例子不能用

// define the new value to add to the cookie
$ad_name = $myProductId; //comes from $_GET[]
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(array_key_exists('recentviews', $_COOKIE)) {
    $cookie = $_COOKIE['recentviews'];
    $cookie = unserialize($cookie);
} else {
    $cookie = array();
}
// add the value to the array and serialize
$cookie[] = $ad_name;
$cookie = serialize($cookie);
// save the cookie
setcookie('recentviews', $cookie, time()+3600);
//prints to screen noting
foreach ($_COOKIE['recentviews'] as $h) {
        echo $h."-";
    }

$_COOKIE['recentviews']仍然是一个序列化的字符串,所以这在循环中不起作用。

工作代码:

// define the new value to add to the cookie
$ad_name = $myProductId; //comes from $_GET[]
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(array_key_exists('recentviews', $_COOKIE)) {
    $cookie = $_COOKIE['recentviews'];
    $cookie = unserialize($cookie);
} else {
    $cookie = array();
}
// add the value to the array and serialize
$cookie[] = $ad_name;
$cookieString = serialize($cookie); /* changed $cookie to $cookieString */
// save the cookie
setcookie('recentviews', $cookieString , time()+3600); /* insert $cookiestring */
//prints to screen noting
foreach ($cookie as $h) { /* changed $_COOKIE['recentviews'] to $cookie */
        echo $h."-";
    }

/* ..*/注释。