PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 13, 2022

[FIXED] How to store a php array inside a cookie?

 January 13, 2022     arrays, cookies, php, variables     No comments   

Issue

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?


Solution

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'



Answered By - Jordan Casey
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing