简体   繁体   中英

multiple cookie data using php (shoping cart)

i'm makeing now a shoping cart, i'm successfully write and read a cookie using php, but i cant add multiple data, how to add more then 1 goods to my shoping cart ?

I gues i shoulf us an array, but how to use it working with cookies? i mean how to read an array from my cookie file. Or maybe have easyer way to slove my problem?

 <?
        setcookie("id", $id);
        setcookie("howmany", $howmany);
        header('Location: http://localhost/shop/index.php?page=shop&id='.$id);
        exit;
    ?>

read like this

<?
    echo('u add id'.$_COOKIE["id"].' as'.$_COOKIE["howmany"].' thank you');
?>

You should not use cookies for that.

Save it all in the users session and only assign the session ID as a cookie. It is enough if the server alone knows about user activity data and only tells the user if nesessary.

Everything else is unsafe and cookies have the nasty problem that you dont know if they are rejected except you reload the page.

Cookies can also be accessed without knowing a useraccount/password and you can see what other users of the same PC bought or tried to buy some time ago if they dont expire in time.

I cannot imagine that you want that, do you?

COOKIE has size and count limitation, so you can try SESSION

Reference What is the maximum size of a web browser's cookie's key?

Maximum number of cookies allowed

I think session would be the better option, because it's easier to use and more secure.

So if you want to store arrays in cookie, it is possible with json_encode / json_decode php functions. Let's say you have an array:

$arr = array(1, 2, 3);

To save it in cookie you have to write:

setcookie('some_key', json_encode($arr));

And to modify:

$arr = json_decode($_COOKIE['some_key']);
$arr[0] = 4;
setcookie('some_key', json_encode($arr));

Much easier to use sessions. Somewhere in the beginning of the script you can write:

session_start();

And then simply:

$_SESSION['some_key'] = array(1, 2, 3);
$_SESSION['some_key'][0] = 4;

But there is a caveat: session_start has to be called before any output, eg: echo 'some text' . It's good to place session_start in the very beginning of the script.

And cookie is only a good option if you want this data to be accessible from javascript, that's all.

Good luck

UPDATE: More about php sessions you can read here

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