John Davidson

How to store a php array inside a cookie?

0 comments
Message:


I'm trying to create a php to do list using cookies, however am struggling to store the cookie inside an array so that I can add more than one cookie.


When I submit the form, a cookie is added, but when I go to add another the first one is replaced.


I want to store the cookie in a variable, push it to an array then save it to the end of the list rather than replace the current cookie.


Here is the code I have so far:


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

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

$tasks = array ();

if(isset($_COOKIE[$task])) {

array_push($tasks, $task);

echo $_COOKIE[$task];

} else {

}

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

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

I'm not sure on exactly where I'm going wrong, would anyone be able to help?



My Answer:
You are currently overwriting the cookie each time you submit the form because you are setting the cookie with the same name 'task' each time. Instead, you can store the tasks in an array and then serialize the array before storing it in the cookie.

Here is an updated version of your code:

php
if (isset($_POST['submit'])) {
$task = htmlentities($_POST['task']);

if(isset($_COOKIE['tasks'])) {
$tasks = unserialize($_COOKIE['tasks']);
} else {
$tasks = array();
}

$tasks[] = $task;

setcookie('tasks', serialize($tasks), time() + 3600);

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


In this code, we first check if the 'tasks' cookie exists. If it does, we unserialize the cookie value into an array. If it doesn't exist, we initialize an empty array. We then add the new task to the array and serialize the array before storing it in the 'tasks' cookie.

When you want to display the tasks, you can unserialize the cookie value and loop through the array to display each task.

Rate this post

3 of 5 based on 8822 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us