I need that the last 3 searches are saved in a cookie and displayed

本秂侑毒 提交于 2021-01-07 02:53:40

问题


I want the last 3 searches to be saved in a Cookie and displayed in a '< p>' tag. Here is my HTML code:

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

I only managed to display the previous search but I don't know how to do the 2 previous ones, here is my php code:

<?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>'; 
?>

回答1:


There are multiple ways to achieve this. While I'd prefer the database approach, I'll keep it simple and show you the serialize approach.

What you currently have in your Cookie: the last search.
What you want in your Cookie: the last three searches.

So, we need an array in the Cookie. But we can't put a plain array inside. There are a few workarounds for this. I'll use the serialize approach. But we could also work with json, comma separated lists, ...

Your code should do something like this:

// 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);

My code is untested, as I didn't work with cookie for ages. But it should work.



来源:https://stackoverflow.com/questions/65296033/i-need-that-the-last-3-searches-are-saved-in-a-cookie-and-displayed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!