反序列化cookie变量

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.

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

You can change only this part of your code:

if(!$_COOKIE['mycookie']){
setcookie('mycookie', $beforecookie, time()+3600);
}

Then reload the page...

This piece of code:

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

The cookie that you set won't be available to the code until the browser refreshes the page.

Also, if you really want to do this, make sure to add a checksum to the cookie that's based on a server-side secret and the contents of the data you're saving into the cookie. Look into hash_hmac(). Blindly unserializing a value that you receive from an untrusted source is simply irresponsible.

If you want to have your cookie available instantly (and not after page refresh like the others said) just add

$_COOKIE['mycookie'] = $beforecookie;

right after this line

setcookie('mycookie', $beforecookie, time()+3600);

Your cookie will be instantly available :-)

Need to use base64_encode() after function serialize().

set:

setcookie('name', base64_encode( serialize( $arr ) ) );

get:

unserialize( base64_decode( $_COOKIE['name']) );