Home > other >  How to store a php array inside a cookie?
How to store a php array inside a cookie?

Time:01-08

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?

CodePudding user response:

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'

CodePudding user response:

There are a few things wrong with your code. First of all, you cannot story an array in a cookie, only strings. Whay you can do is transform your cookie to JSON when setting it, and when you are getting it decode it. Also, when pushing to you array, the array you are pushing to is reset on every request. To get around this, first get you data from the cookie. Something like this is what I would use:

const COOKIE_NAME = 'tasks';

$tasks = ['one', 'two'];
setcookie(COOKIE_NAME, json_encode($tasks));

$newTask = 'another task';

if (isset($_COOKIE[COOKIE_NAME])) {
    $tasks = json_decode($_COOKIE[COOKIE_NAME], true);
    array_push($tasks, $newTask);
    setcookie(COOKIE_NAME, json_encode($tasks));
}

var_dump(json_decode($_COOKIE[COOKIE_NAME], true)); // Every request after the first time a cookie is set "another task" is added to the cookie. 
  •  Tags:  
  • Related