Question

I have a classifieds site, and on the main page I want the last visited ads by the existing user to show up.

How would I do this?

Basically, it has to be something like this:

  1. User clicks on an ad.
  2. The ad ID gets saved in a cookie.
  3. Then, when clicking on another ad, that ad ID gets saved also.
  4. Then, whenever visiting the main page, those ads will be displayed by fetching the AD ID:s from the cookie.

Is it even possible to add values to an existing cookie ?

Was it helpful?

Solution

Cookies basically work like this: to set a cookie, the server sends its name and value to the client with a HTTP header in any HTTP response. After that, the client will send that key and value as a HTTP header with every request to that server.

So in order to "add" a value to a cookie, all you have to do is read the current value which was sent to you with the current request, add the new data, and set the result as a cookie with the same key in your response.

OTHER TIPS

you can use the string concatenate operator:

setcookie('ad_ids', $_COOKIE['ad_ids'] . ';'.$new_id);

Use an array of viewed classifieds:

$arr = array('1', '2', '3');

setcookie('viewedads', serialize($arr), time()+10000, '/');

then if you want to add more ads:

$arr = unserialize($_COOKIE['viewedads']);
//new add
$arr[] = '4';

setcookie('viewedads', serialize($arr), time()+10000, '/');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top