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>';
?>
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:
My code is untested, as I didn't work with cookie for ages. But it should work.