Jump to content

Array in a cookie


heavyEddie

Recommended Posts

I'm trying to work with cookies for the first time.  It seems like it should be simple enough, but alas, I'm having some problems.

[code] for($i = 0; $i < count($_POST['pid']); $i++)
{
$cookie_name = 'cart_item[' . $_POST['pid'][$i] . ']';
setcookie($cookie_name, $_POST['qty'][$i], 0, '/');
}
[/code]

I'm trying use cookies to store an array.  The code seems to work as long as I'm setting all the cookies on the page at one time.  For instance...
[list]
[*]If I set a cookie called cart_item[22] = 2 it works fine.
[*]If I set cookies called cart_item[22] =2  and another called cart_item[33] = 3 they are both stored fine.
[*]However, if  cart_item[22] is already set and the script is run to set cart_item[33]... it appears cart_item[22] is overwritten with cart_item[33].
[/list]

Link to comment
https://forums.phpfreaks.com/topic/27044-array-in-a-cookie/
Share on other sites

You can store it in a single value...

// set it

[code]$items = array ();

for ( $i = 0; $i < sizeof ( $_POST['pid'] ); $i++ )
{
$items[$_POST['pid'][$i]] = $_POST['qty'][$i];
}

if ( ! empty ( $items ) )
{
setcookie ( 'store_cart' urlencode ( serialize ( $items ) ), 0, '/', '.domain.com' );
}[/code]

// extract it...

[code]$cart = array ();

if ( isset ( $_COOKIE['store_cart'] ) )
{
$cart = unserialize ( urldecode ( $_COOKIE['store_cart'] ) );
}[/code]



Link to comment
https://forums.phpfreaks.com/topic/27044-array-in-a-cookie/#findComment-123669
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.