【问题标题】:How to store last visited n pages in cookie in PHP如何在PHP中的cookie中存储最后访问的n个页面
【发布时间】:2014-10-15 18:37:39
【问题描述】:

我用谷歌搜索了 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."-";

    }

【问题讨论】:

  • 什么鬼?为什么-1
  • 在输出任何 html 内容(或空白)之前,您是否进行了所有这些 cookie 设置?
  • 您也可以使用/调试:$result = setcookie(...); 结果是真/假,取决于它是否正确执行。

标签: php cookies session-cookies setcookie


【解决方案1】:

$_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."-";

    }

更改在 /* .. */ cmets 中解释。

【讨论】:

  • 请详细说明-1?
猜你喜欢
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2014-04-24
相关资源
最近更新 更多