tags:

views:

248

answers:

3

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 ?

+3  A: 

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.

Michael Borgwardt
A: 

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, '/');
dfilkovi
A: 

you can use the string concatenate operator:

setcookie('ad_ids', $_COOKIE['ad_ids'] . ';'.$new_id);
knittl
Are you sure that writing to $_COOKIE actually sends a cookie on the client?
Michael Borgwardt
now you mention it …
knittl