Storing and Retrieving an Array in a PHP Cookie

Storing and retrieving an array in a PHP cookie

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.

Storing PHP arrays in cookies

Serialize data:

setcookie('cookie', serialize($info), time()+3600);

Then unserialize data:

$data = unserialize($_COOKIE['cookie'], ["allowed_classes" => false]);

After data, $info and $data will have the same content.

How to store a php array inside a cookie?

When you store a cookie with the same name, it gets overwritten. You also seem to be storing the individual task and not the array. If you would like to store the array safely, you can attempt to store it as JSON.

It would look like this:

if (isset($_POST['submit'])) {

$task = htmlentities($_POST['task']);

//Check if the cookie exists already and decode it if so, otherwise pass a new array
$tasks = !empty($_COOKIE['tasks']) ? json_decode($_COOKIE['tasks']) : [];
//if(isset($_COOKIE[$task])) {

array_push($tasks, $task);

// echo $_COOKIE[$task];

//}

$encodedTasks = json_encode($tasks);

setcookie('task', $encodedTasks, time() + 3600);

header('Location: index.php');
}

You seem to be checking if the value of the post variable is a key in your array rather than using the 'tasks' key as you set in your setcookie. You do not need to see if the array exists again as you passed either the decoded array or the empty array as 'task'

How to create cookie as array

$search_array=array(
'category'=>array('cat', array($catid)),
...
);

in 48 hours

setcookie("search", $s_array, time()+(3600*48));  

PHP array to cookie breaks on space

The cookies must be urlencoded - use urlencode().

UPDATE

Well, setcookie() urlencodes the data internally, so the problem is somewhere else!

PHP how to stringify array and store in cookie

NEVER EVER USE serialize with User input! serialize calls __wakeup and is a big security vulnerability, because you can execute code on the server. (Now the rules before you break 'em)

there is a serialize/unserialize function to convert an array to a string and back.

Edit:
When you store a string to cookie (setcookie), php needs to do a url encode on the string. This prevents any characters in the string saved to cookie interfering with any other headers. When the page is loaded next, php gets the cookie and automatically does a url decode on the cookie value to return it to it's previous value. As far as what is stored in the cookie, this shouldn't matter within php because php will do the url encode/decode automatically. Now if you are getting the cookie in another language such as javascript, then yes, you will get the raw string back. In this case you can use something like decodeURI in JS to get the original value back.

how to put a Cookie into an array?

Answer

You can store cookies using array syntax and read them as a multi-dimensional arrays:

setcookie('array[key]', 'value');
$var = $_COOKIE['array']['key'];

Your code would look like this:

for($val as $key=>$value)
setcookie('vals['.$key.']', $value, time()+60*60*24*365);


Multi-Dimensional Arrays

You can also store multi-dimensional arrays the same way:

setcookie('array[key1][key2]', 'value');
$var = $_COOKIE['array']['key1']['key2'];


Clearing the Cookie

When you need to clear out the cookie, there are multiple methods; the longest being:

for($_COOKIE['array'] as $key=>$value)
setcookie('array['.$key.']', '', time()-60*60*24*365);

The easiest and most preferable way is this:

setcookie('array', '', time()-60*60*24*365);


Conclusion

Cookies allow arrays to be stored using standard array syntax. Storing a multi-dimensional array is also standard syntax.

To destroy a cookie with an array value, use the same syntax as for a normal cookie, either over the whole array or on each specific element.

The documentation on setcookie() goes over this.

Pass PHP array into cookie and retrieve with jQuery

There are some points which i want you to check

  • Make sure cookie plugin is loaded , best to load it after jquery.
  • Now regarding whitespaces before setcookie , much of this depends on you buffering setting if you have output buffering on then you can put anything or echo wherever and wherever you want and cookie header will still be sent but if its "Off" any <script> <style> <html> in short anything that comes before your posted php code is likely to cause problems .Check in your php.ini output_buffering=value if value is not "Off" and rather some number then you are clear here ; note that whitespaces inside <?php ?> don't matter just display function like echo,print_r etc do if they come before setcookie().
  • Also check the scope of $wnDropdownmake sure it's global and exists with some value when you call setcookie.


Related Topics



Leave a reply



Submit