Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing and retrieving an array in a PHP cookie

I'm looking to store some data from some 'virtual' index cards. Each card has a front and a back, and the user can store multiple cards. Each side will have data on it.

I ----------------- I I CARD 1 FRONT I I------------------I
I --------------- I I CARD 1 BACK I I-----------------I
I ----------------- I I CARD 2 FRONT I I------------------I
I --------------- I I CARD 2 BACK I I-----------------I

OK, my diagrams got messed up a bit. But you get the message. :)

Imagine it from the diagrams above. I'd like to store each card's data (front and back) in a cookie, as an array (maybe), and then be able to pull each value back and insert it where applicable (on a different page).

At the same time, bear in mind that the user can make as many cards as they like. I can't use POST or GET functions. The array bit is debatable, if you can think of an easier way of storing this data in a cookie, let me know. Please note: don't suggest storing in a database, as it won't be convenient for the project. :)

like image 873
728883902 Avatar asked Sep 28 '13 15:09

728883902


People also ask

Can we store array in cookie in PHP?

Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system. Consider explode() to set one cookie with multiple names and values.

Can you store an array in a cookie?

Cookies can only store string values. You cannot store an array directly into a cookie.

Where is the cookie data stored in PHP?

Cookies are always stored in the client. The path only sets restrictions to what remote pages can access said cookies. For example, if you set a cookie with the path "/foo/" then only pages in the directory "/foo/" and subdirectories of "/foo/" can read the cookie.

How cookies are extracted using PHP?

Accessing Cookies with PHP Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example. You can use isset() function to check if a cookie is set or not.


3 Answers

Use json_encode / json_decode to get / set arrays in cookies.

Test array

$cardArray=array(
    'CARD 1'=>array('FRONT I', 'BACK I'),
    'CARD 2'=>array('FRONT 2', 'BACK 2')
);

convert and write the cookie

$json = json_encode($cardArray);
setcookie('cards', $json);

the saved string looks like this

{"CARD 1":["FRONT I","BACK I"],"CARD 2":["FRONT 2","BACK 2"]}

get the cookie back

$cookie = $_COOKIE['cards'];
$cookie = stripslashes($cookie);
$savedCardArray = json_decode($cookie, true);

show the restored array

echo '<pre>';
print_r($savedCardArray);
echo '</pre>';

outputs

Array
(
    [CARD 1] => Array
        (
            [0] => FRONT I
            [1] => BACK I
        )

    [CARD 2] => Array
        (
            [0] => FRONT 2
            [1] => BACK 2
        )

)

Edit
If you wonder about stripslashes, it is because the string saved actually is

{\"CARD 1\":[\"FRONT I\",\"BACK I\"],\"CARD 2\":[\"FRONT 2\",\"BACK 2\"]}

setcookie adds \ before quoutes to escape them. If you not get rid of those, json_decode will fail.


Edit II

To add a new card to the cookie

  1. load the array as above
  2. $savedCardArray['CARD XX']=array('FRONT XX', 'BACK XX');
  3. save the array as above, but now of course $savedCardArray and not $cardArray.
like image 199
davidkonrad Avatar answered Oct 13 '22 20:10

davidkonrad


Serialize/Unserialize works as a simpler alternative to json_encode / json_decode

setcookie('cookiename', serialize(array), ...) to save to cookie.

array = unserialize($_COOKIE['cookienam']) to retrieve array.

like image 23
Jules Bartow Avatar answered Oct 13 '22 18:10

Jules Bartow


Play with something like this

<?php

$card_id = '123';
$value = 'im a black lady';

setcookie("card[$card_id][front]", $value);

// reload page to actually read the cookie

echo $_COOKIE['card'][$card_id]['front']; // im a black lady

?>
like image 2
Tom Avatar answered Oct 13 '22 20:10

Tom