Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.