【问题标题】:I need that the last 3 searches are saved in a cookie and displayed我需要将最后 3 次搜索保存在 cookie 中并显示
【发布时间】:2020-12-16 02:41:32
【问题描述】:

我希望将最后 3 次搜索保存在 Cookie 中并显示在“

”标签中。 这是我的 HTML 代码:

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

我只设法显示了以前的搜索,但我不知道如何执行前两个搜索,这是我的 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>'; 
?>

【问题讨论】:

  • 看看序列化。我想,它会帮助你
  • 我查看了 serialize 但我不知道它如何帮助解决我的问题

标签: php search cookies session-cookies cookie-session


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 2014-11-07
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    相关资源
    最近更新 更多