简体   繁体   中英

Delete value in cookie array

I have an cookie array with json items like this

//set my cookie

setcookie("my_Cookie", $cookie_content, time()+3600);

//this is the content of my cookie for example with 2 items
[{"item_id":"9","item_tag":"AS","session_id":"554obe5dogsbm6l4o9rmfif4o5"},{"item_id":"6","item_tag":"TE","session_id":"554obe5dogsbm6l4o9rmfif4o5"}]

The workflow is like an shopping cart, I can add and delete items. One "product" on my website contains: item_id, item_tag and the session_id;

For adding an item the cookie will be extended with item_id":"X","item_tag":"X","session_id":"X

now if I click on delete I want remove the current three values in the cookie

I try it with

unset($_COOKIE["my_Cookie", 'item_id'=> $item_id, 'item_tag'=> $item_tag, 'session_id'=> $session_id]); but this doesn't work

Is it possible to delete specific values of my cookie?

Like this:

setcookie('cookie_name'); // Deletes the cookie named 'cookie_name'.

This works because setting a cookie with no value is the same as deleting it.

If I'm not mistaken, you can't directly modify a cookie's value; you'll have to read the value, make any modifications, and then replace the cookie using the same name.

So, in this case, once a user hits the delete link, your script should save the ID of the item that they want removed, read the cookie value(s), rewrite the array and then replace the cookie with the updated values.

Perhaps this demo will help:

// Should be the user submitted value to delete.
// Perhaps a $_GET or $_POST value check.
$value_to_delete = 9;  

// Should be the cookie value from $_COOKIE['myCookie'] or whatever the name is.
// Decode from JSON values if needed with json_decode().
$cookie_items = array( 
    array("item_id" => 9, "item_tag" => "RN"), 
    array("item_id" => 6, "item_tag" => "RN"), 
    array("item_id" => 4, "item_tag" => "RN")
);

// Run through each item in the cart 
foreach($cookie_items as $index => $value)
{
    $key = array_search($value_to_delete, $value);

    if($key == "item_id")
    {
        unset($cookie_items[$index]);
    }
}

// Reset the index
$cookie_items = array_values($cookie_items);

// Set the cookie
setcookie($cookie_items);

// Debug to view the set values in the cookie
print_r($cookie_items);

我相信Cookie只会以字符串形式存储,因此最好将其覆盖...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM