Search code examples
phparraysserializationcookiessetcookie

Unserialize cookie variable


Thank for viewing my question.

the code:

$array = array("zero","one","true","three");
echo $beforecookie = serialize($array); //<<-- IT WORKS;
print_r(unserialize($beforecookie)); //<<--IT WORKS

setcookie('mycookie', $beforecookie, time()+3600);
echo $aftercookie = $_COOKIE['mycookie']; // <<-- it works perfectly same with $beforecookie

$data = unserialize($aftercookie);
print_r($data); //<<--RETURN NOTHING (the problem)
var_dump($data); //<<-- RETURN bool(false);

The string(serialized from the array) that I got from cookie can't be unserialized; why? how can I get the array back after set it to the cookie with serialize()? or maybe I missed something?

Thanks for the help.


Solution

  • Cookie sets after script execution as well as headers, so you can't access it before page reload.