如何在 cookie 中存储 php 数组?

How to store a php array inside a cookie?

我正在尝试使用 cookie 创建一个 php 待办事项列表,但是我很难将 cookie 存储在一个数组中,以便我可以添加多个 cookie。

当我提交表单时,添加了一个 cookie,但是当我去添加另一个时,第一个被替换。

我想将 cookie 存储在一个变量中,将其推送到一个数组中,然后将其保存到列表的末尾,而不是替换当前的 cookie。

这是我目前的代码:

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');
}

我不确定我到底哪里出错了,有人能帮忙吗?

当您存储具有相同名称的 cookie 时,它​​会被覆盖。您似乎也在存储单个任务而不是数组。如果您想安全地存储数组,可以尝试将其存储为 JSON.

看起来像这样:

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');
}

您似乎在检查 post 变量的值是否是数组中的键,而不是使用您在 setcookie 中设置的 'tasks' 键。当您将解码数组或空数组作为 'task'

传递时,您不需要查看数组是否再次存在

您的代码有一些问题。首先,你不能在 cookie 中描述数组,只能描述字符串。您可以做的是在设置时将 cookie 转换为 JSON,并在获取它时对其进行解码。此外,当推送到您的数组时,您推送到的数组会在每次请求时重置。要解决这个问题,首先要从 cookie 中获取数据。我会用这样的东西:

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.