0

我希望将最后 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>'; 
?>
4

1 回答 1

0

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

您当前在 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 了。但它应该工作。

于 2020-12-15T07:16:44.787 回答