-1

I want to store an array into a cookie using the set_cookie() function. So whenever I pass an array as an argument to the set_cookie() function it returns an error:

Warning: setcookie() expects parameter 2 to be string, array given in C:\xampp\htdocs\folder\sajjad.php on line 3.

I already tried all the answers available in StackOverflow regarding this topic. But none of them are working.

<?php  
    $val = array('1','2','3','4');
    setcookie("sajjad",$val,time()+(86400*30));
?>
<!DOCTYPE html>
<html>
<head>
    <title>HOME</title>
</head>
<body>

</body>
</html>
M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
  • 1
    As the error suggests, cookie data must be in string format. More importantly, you shouldn't store real data in a cookie, because the user can edit them.instead you may use sessions – NanThiyagan Jan 08 '19 at 11:30
  • Welcome on SO. You could [`json_encode`](https://secure.php.net/manual/en/function.json-encode.php) you array. But as said in a previous comment, you should avoid storing real datas in your cookies. Using [sessions](https://secure.php.net/manual/en/session.examples.basic.php) is better. – Anthony Jan 08 '19 at 11:33
  • 1
    _"I already tried all the answers available in StackOverflow regarding this topic"_ - What have you tried and how did it not work? Cookies can only store strings and numbers so you need to serialize the array. You can either use PHP's `serialize()` (and then `unserialize()` when reading the value again) or store it as a json string using `json_encode()` and `json_decode()`. As the first comment suggests though, you should only use cookies to store small amount of data that isn't critical or private since it can be modified by the client. – M. Eriksson Jan 08 '19 at 11:34
  • “php storing array in a cookie” typed into Google leads to https://stackoverflow.com/questions/9032007/arrays-in-cookies-php in no time, and that should really give you all the info you need. – misorude Jan 08 '19 at 11:48

2 Answers2

1

You can use serialize to convert your data to a form that can be stored in a cookie. e.g.

$val = array('1','2','3','4');
setcookie("sajjad",serialize($val),time()+(86400*30));

to get the value back again, use unserialize:

$val = unserialize($_COOKIE['sajjad'], false);

As has been pointed out in the comments, it is unsafe to store data in cookies as they can be modified by the user. It is safer to use session variables. You can find information on how to do that here.

Nick
  • 138,499
  • 22
  • 57
  • 95
1
    $val = array('1','2','3','4');
    $data = serialize($val); //serialize array 
    setcookie("sajjad",$data,time()+(86400*30));
    $retrive_data = unserialize($_COOKIE['sajjad']);//unserialize array
    print_r($retrive_data);//print given array