19

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. :)

halfer
  • 19,824
  • 17
  • 99
  • 186
728883902
  • 507
  • 1
  • 4
  • 21
  • See http://stackoverflow.com/questions/7413161/store-array-in-cookie – Mihai8 Sep 28 '13 at 15:09
  • Do you have a code example since the poster said his code was wrong? I can't quite work out where the semicolons would fit. – 728883902 Sep 28 '13 at 15:17
  • reg PS : Cant se why - your question has perfectly SO relevancy, but try ask on meta – davidkonrad Sep 28 '13 at 15:25
  • show an example of the array – davidkonrad Sep 28 '13 at 15:27
  • Well, I'd like to store the front value and the back value of each card, so for example: CARD 1 FRONT CARD 1 BACK CARD 2 FRONT CARD 2 BACK ...but the user can create an almost unlimited number of cards. :) – 728883902 Sep 28 '13 at 15:36
  • @MajidFouladpour, why did you insert off topic "Data" values? – davidkonrad Apr 20 '15 at 16:45
  • @davidkonrad if you believe they are off topic you could remove them. I reasoned those are the actual sample data that a user stored on the cards, as using cards to store 'Card 1 Front', 'Card 1 Back' is not of much use. – Majid Fouladpour Apr 20 '15 at 21:48
  • @MajidFouladpour, I do not "believe" changing the entire fundamentals of the question is wrong, it **IS** wrong. Reasons for edting a question is amongst other things ["To clarify the meaning of the post (**without changing that meaning**)"](http://stackoverflow.com/help/editing) when you are changing the meaning of a question, you are also compromising the validity of all answers to that question. – davidkonrad Apr 21 '15 at 05:41

3 Answers3

48

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.
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
  • 1
    you are welcome! See edit for expl about stripslashes, forgot that. – davidkonrad Sep 28 '13 at 15:53
  • Ah yes, that explains. One more question... How do I print/echo Card 1's front and back result? Would card 1 be the variable and then [0] print Card 1's front? – 728883902 Sep 28 '13 at 15:59
  • Yes! `echo $savedCardArray['CARD 1'][0].' '.$savedCardArray['CARD 1'][1];` wil output `FRONT I BACK I` – davidkonrad Sep 28 '13 at 16:04
  • Will the count function work to count how many cards the user has made? – 728883902 Sep 28 '13 at 16:10
  • 1
    Yes. The result is a perfectly normal array - `count($savedCardArray)` and all other array functions is available. – davidkonrad Sep 28 '13 at 16:13
  • Tried the code and it seems to work well. :) I got a bit confused, though, when the user adds a new card. I understand I must pull back the cookie and add the new card - once I've returned the cookie, what is a logical way to add the new card data to the cookie? – 728883902 Sep 28 '13 at 16:23
  • see update. But this is really very basic :) BTW, Stackoverflow dont like multiple comments (you may have seen a message below) – davidkonrad Sep 28 '13 at 16:30
  • 1
    The second parameter for json_encode should not be "true". That would be the second parameter on json_decode. – Darryl Aug 14 '14 at 21:28
3

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.

Jules Bartow
  • 956
  • 14
  • 14
2

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

?>
Tom
  • 691
  • 4
  • 7
  • Thank you! :) With regards to the Card ID, how would I extract that/store multiple card values? Sorry for a lack of understanding. – 728883902 Sep 28 '13 at 15:44
  • You need some kind of unique id to identify each card and their front/back values. How you define that depends on your structure. Perhaps set cards with user id and start with user card 1 and increase +1 for each card the user have. You can count($_COOKIE['user_id']) and step up card number from count result, or simply number them without user identification if thats sufficient. – Tom Sep 28 '13 at 16:05