How do I use cookies to store users' recent site history(PHP)?

Posted by ggfan on Stack Overflow See other posts from Stack Overflow or by ggfan
Published on 2010-05-11T19:03:53Z Indexed on 2010/05/11 19:14 UTC
Read the original article Hit count: 201

Filed under:
|

I decided to make a recent view box that allows users to see what links they clicked on before. Whenever they click on a posting, the posting's id gets stored in a cookie and displays it in the recent view box.

In my ad.php, I have a definerecentview function that stores the posting's id (so I can call it later when trying to get the posting's information such as title, price from the database) in a cookie. How do I create a cookie array for this?

        **EXAMPLE:** user clicks on ad.php?posting_id='200'

     //this is in the ad.php
     function definerecentview()
     {

         $posting_id=$_GET['posting_id'];
         //this adds 30 days to the current time
         $Month = 2592000 + time();
         $i=1;
         if (isset($posting_id)){
                      //lost here
             for($i=1,$i< ???,$i++){             
                 setcookie("recentviewitem[$i]", $posting_id, $Month);
             }
         }
     }


     function displayrecentviews()
     {
        echo "<div class='recentviews'>";
        echo "Recent Views";
        if (isset($_COOKIE['recentviewitem'])) 
        {
            foreach ($_COOKIE['recentviewitem'] as $name => $value) 
            {
                echo "$name : $value <br />\n"; //right now just shows the posting_id
            }
        }
        echo "</div>";
     }

How do I use a for loop or foreach loop to make it that whenever a user clicks on an ad, it makes an array in the cookie? So it would be like..

1. clicks on ad.php?posting_id=200 --- setcookie("recentviewitem[1]",200,$month);
2. clicks on ad.php?posting_id=201 --- setcookie("recentviewitem[2]",201,$month);
3. clicks on ad.php?posting_id=202 --- setcookie("recentviewitem[3]",202,$month);

Then in the displayrecentitem function, I just echo however many cookies were set?

I'm just totally lost in creating a for loop that sets the cookies. any help would be appreciated

© Stack Overflow or respective owner

Related posts about php

Related posts about cookies