PHP cookie value question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
leosylai
Forum Newbie
Posts: 1
Joined: Fri Mar 06, 2015 1:51 am

PHP cookie value question

Post by leosylai »

I have the following php codes and want to echo the cookie array item number.

<?php
$product_id = $item;
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(array_key_exists('recentviews', $_COOKIE)) {
$cookie = $_COOKIE['recentviews'];
$cookie = unserialize($cookie);
} else {
$cookie = array();
}

// add the value to the array and serialize
$cookie[] = $product_id;
$cookie = serialize($cookie);

// save the cookie
setcookie('recentviews', $cookie, time()+3600);
?>
COOKIE: <?php echo $cookie; ?>

I can see the $cookie value.
However, I use use the method listed below but cannot get the answers I need.
<?php
$recent3 = $cookie[0];
$recent2 = $cookie[1];
$recent1 = $cookie[2];
?>

Please help me resolve this question, thank you in advance.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP cookie value question

Post by requinix »

Where are you putting that code? In the first part you reuse $cookie and it can be either the serialized string or an array.

And you should know: what you're doing is not safe. The user can edit their own cookies and that means they can trick your code into unserialize()ing bad data that can cause all sorts of problems for you.
Use the session, not a cookie.
Post Reply