Allen McCabe schreef:
> I have a shopping cart type system set up which keeps track of the cart
> contents using a SESSION variable, where $_SESSION['cart'][$item_id'] is
> equal to the quantity, so the name/value pair is all the information I need.
> But sessions are unreliable on the free server I am currently using for this
> website (not my choice), so I had start using cookies because users were
> being sporadically logged out, sometimes just on a page refresh.
> I want to find a way to set a cookie to remember the cart items as well, and
> I thought setting a cookie for each item/quantity pair was the way to go
> until I started trying to figure out how to unset all those cookies if the
> user empties their cart.
> Is there any way to set cookies with an array for the name? Intead of
> $_COOKIE['item_number'] have $_COOKIE['cart']['item_number'] like I have the

1. use one cookie for this (and other data)
2. DO NOT USE serialize()/unserialize() to pack/extract the data

using unserialize() opens you up to alsorts of potential hacks (IMHO), keep the 
structure simple and revalidate it's entire contents everytime you read it in
(assuming your article ids are INTs, all the data should be [valid] INTs - 
else and the cookie should be deleted).

here is some code to play with: (written directly in my email client, no 
garantees is
parses or works as is)


function buildCookieCartStr(array $data)
        $out = array();
        foreach ($data as $artId => $quant)
                $out[] = $artId.':'.$quant;

        return join('|', $out);

function parseCookieCartStr($s)
        $data  = array();
        $items = explode('|', $s);

        if (!is_array($items))
                return killCookieCart();

        if (count($items)) foreach ($items as $item) {
                $item = explode(':', $item);

                if (is_array($item) || count($item) !== 2)
                        return killCookieCart();                

                foreach ($item as $v)
                        if (!$v || ($v != (int)$v))
                                return killCookieCart();

                if (!isValidArtId($item[0]) || ($item[1] < 1)
                        return killCookieCart();

                if (isset($data[ $item[0] ]))
                        return killCookieCart();

                $data[ $item[0] ] = $item[1];

        return $data;

function killCookieCart()
        // TODO: delete cookie

function isValidArtId($id)
        return true; // TODO: valid article id


you can secure your code further by using the filter extension in combination
with a regexp filter in order to retrieve the cookie data from the request,
here's a regexp that matches only non empty strings with digit, colon and pipe 


PS - hello again list.

PHP General Mailing List (
To unsubscribe, visit:

Reply via email to