Php 限制cookie中的数组大小

Php 限制cookie中的数组大小,php,cookies,Php,Cookies,我有以下功能,可以在用户访问我网站的每个产品页面上设置cookie function setcookie() { $entry_id = '787'; if (isset($_COOKIE['recently_viewed'])) { $currentSession = unserialize($_COOKIE['recently_viewed']); if (!in_array($entry_id, $currentSession)) {

我有以下功能,可以在用户访问我网站的每个产品页面上设置cookie

function setcookie() {

    $entry_id = '787';

    if (isset($_COOKIE['recently_viewed'])) {

        $currentSession = unserialize($_COOKIE['recently_viewed']);

        if (!in_array($entry_id, $currentSession)) {

            if (count($currentSession) > 5) {
                unset($currentSession[0]);
            }

            $currentSession[] = $entry_id;

        } else {}

        $currentSession = serialize($currentSession);
        setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');

    } else {

        $recently_viewed[] = $entry_id;
        $currentSession = serialize($recently_viewed);
        setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');

    }

}
在这个函数中,我试图限制cookies数组中存储的项目数

当cookies数组中有6个项目时,我希望删除该数组中的第一个(最早的)项目,然后添加新项目(因此,项目不会超过6个,而是始终添加新项目)

我使用了以下方法,但似乎并不总是有效。有时,当有超过5个项目时,它会删除第一个项目,但其他时候,它只是不断添加这些项目,以便有超过6个项目

if (count($currentSession) > 5) {
    unset($currentSession[0]);
}

有谁能告诉我有没有更好的方法来实现这一点吗?

您肯定应该使用session

if (count($currentSession) > 5) {
    $arr = array_shift($currentSession);
}
session_start();
$entry_id = '788';
if (!is_array($_SESSION['recently_viewed'])) {
    $_SESSION['recently_viewed'] = array();
}
//  add the item to the begining
array_unshift($_SESSION['recently_viewed'], $entry_id);
// ensure unique entries
$_SESSION['recently_viewed'] = array_unique($_SESSION['recently_viewed']);
// keep first 5 entries
$_SESSION['recently_viewed'] = array_slice($_SESSION['recently_viewed'], 0, 5);
echo 'recent: ' . print_r($_SESSION['recently_viewed'], true);

这些数据最好保存在
$\u SESSION
中,否则会发送大量多余的HTTP数据。这是个好主意,但会话的有效期是多久?我刚读到它没有饼干那么长,只要你告诉它就行。它使用cookie来标识会话,因此。。。是的,XD这基本上是一把小小的钥匙,用来打开一个潜在的巨大信息库,而不是每次都来回携带这些信息。你能解释一下它的作用吗?这是使用会话的整个函数的示例吗?谢谢。这太棒了。