我需要将最后3次搜索保存在cookie中并显示



我希望最后3个搜索保存在Cookie中,并显示在'<p>'标签这是我的HTML代码:

<form class="Dform" method="POST" action="index.php">
<input type="text" name="search" value="">
<input type="submit" name="" value="Search">
</form>

我只显示了之前的搜索,但我不知道如何进行之前的2次搜索,这是我的php代码:

<?php
if (!empty($_POST['search']))
{
setcookie('PreviousSearch', $_POST['search'], time()+60*60,'',localhost);
}
?>
<?php
$r1 = htmlspecialchars($_COOKIE['PreviousSearch']);
echo '<p> Previous search (1) : '.$r1.'</p>'; 
?>

有多种方法可以实现这一点。虽然我更喜欢数据库方法,但我会保持简单,并向您展示序列化方法。

您当前Cookie中的内容:上次搜索
您想要Cookie中的内容:最后三次搜索。

所以,我们需要Cookie中的一个数组。但是我们不能在里面放一个简单的数组。有一些解决办法。我将使用serialize方法。但是我们也可以使用json,逗号分隔的列表。。。

你的代码应该这样做:

// Gets the content of the cookie or sets an empty array
if (isset($_COOKIE['PreviousSearch'])) {
// as we serialize the array for the cookie data, we need to unserialize it
$previousSearches = unserialize($_COOKIE['PreviousSearch']);
} else {
$previousSearches = array();
}
$previousSearches[] = $_POST['search'];
if (count($previousSearches) > 3) {
array_shift($previousSearches);
}
/*
* alternative: prepend the searches
$count = array_unshift($previousSearches, $_POST['search']);
if ($count > 3) {
array_pop($previousSearches);
}
*/
// We need to serialize the array if we want to pass it to the cookie
setcookie('PreviousSearch', serialize($previousSearches), time()+60*60,'',localhost);

我的代码未经测试,因为我已经很久没有使用cookie了。但它应该起作用。

最新更新