This question already has an answer here:
I am trying to add 'recent viewed products' feature in my site. So i want to add the products recently watched in cookie. Setting cookie when user go to detail page of the product. So cookie setting code is in detail page. What i am trying
setcookie('recentviews', $productid, time()+3600,'/')
What i need is
recentviews1 =>1
recentviews2 =>5
recentviews3 =>3
OR
recentviews (
[0] => 1,
[1] => 5,
[2] => 3
)
I tried alot of solutions, like setting cookie in loop, but how to know how many views are already set, so I can increment 'recentviews' and set new cookie.
</div>
you can follow below example
$info[7][5]=1;
$info[8][5]=1;
Serialize data:
setcookie('cookie', serialize($info), time()+3600);
Then unserialize data:
$data = unserialize($_COOKIE['cookie']);
After data, $info and $data will have the same content.
I would probably go about something like this (imagining that the cookie content contains obly safe
data):
# basic cookie structure:
$recent_views = array(
# 'product_id' => 'value',
32324 => 2,
32455 => 23,
);
# to add a value in a request handler:
$recent_views = json_decode($_COOKIE['recentviews']);
$recent_views[ 32342 ] = 32;
setcookie('recentviews', json_encode( $recent_views ), $expi_time );
Error checking left out for brevity.
Json really has the advantage that you can easily decode the cookie in javascript in the browser and even make changes there.. (not what I would do, but still a possibility).
Cheers -