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.
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
- load the array as above
$savedCardArray['CARD XX']=array('FRONT XX', 'BACK XX');
- save the array as above, but now of course
$savedCardArray
and not$cardArray
.
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'
Storing arrays in cookies
How about generating a unique ID, storing it in a cookie, and storing your serialized array and the ID in database?
Example:
// ------------ STORING TO COOKIE AND DATABASE ------------ //
$id = uniqid();
setcookie("id", $id, time()+60*60*24); // 1 day
$serialized = serialize($array);
mysql_query("INSERT INTO yourTable (id, array) VALUES ('$id', '$serialized')");
// ------------ SELECTING FROM DATABASE ------------ //
if(!isset($_COOKIE['id'])) die();
$id = mysql_real_escape_string($_COOKIE['id']);
$result = mysql_query("SELECT array FROM yourTable WHERE id = $id LIMIT 1");
if(!is_resource($result)) die();
$serialized = mysql_result($result, 0);
$array = unserialize($serialized);
Update an array stored in a cookie with a new value each time a page is loaded
Tried your code here, everything works perfectly. Try clearing cookies on your browser, possibly just a local problem
Store a complete array in a cookie
I think you're looking for serialize:
<?php
$a = array(1 => 'a', 2 => 'b', 3 => 'c');
$b = serialize($a);
var_dump($b); ////Returns this string(42) "a:3:{i:1;s:1:"a";i:2;s:1:"b";i:3;s:1:"c";}"
$c = unserialize($b);
print_r($c); //Return the same thing as $a
Try out this code, you use serialize to convert an array to string and then you can easily store it. Then, you unserialize to have the array back !
Doc: http://php.net/manual/fr/function.serialize.php
Related Topics
Read Each Line of Txt File to New Array Element
Serializing PHP Object to Json
Converting a Simplexml Object to an Array
Adding Months to a Date in JavaScript
Fastest Way to Convert String to Integer in PHP
Symfony2 - Force File Download
Is There an Equivalent For Var_Dump (PHP) in JavaScript
PHP: If Internet Explorer 6, 7, 8 , or 9
How to Run a PHP Script Inside a HTML File
Group Array by Subarray Values
PHP Array Merge Two Arrays on Same Key
Doctrine 2 and Many-To-Many Link Table With an Extra Field