Search code examples
phpsearchcookiessession-cookiescookie-session

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


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

Solution

  • 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.