Recently, when I was playing the thinkphp framework, it was really dizzy when I encountered a cookie. I found thinkphp2.0 information on the Internet, saying Think \ Lib \ Think \ Util \ Cookie. class. but actually thinkphp3.0 has moved the cookie to ThinkPHP \ Common \ functions. php.
Recently, when I was playing the thinkphp framework, it was really dizzy when I encountered a cookie. I found thinkphp2.0 information on the Internet, saying Think \ Lib \ Think \ Util \ Cookie. class. but actually thinkphp3.0 has moved the cookie to ThinkPHP \ Common \ functions. in php, use test. php tested the cookie function and found that the cookie will automatically store the array with json_encode connection. as mentioned in the manual, array storage is supported, but it has actually become a josn string, in addition, the original Chinese characters have all become characters such as "\ UXXXX", which is very strange. later I checked the original code of the cookie function and found that the characters were converted to json_encode and re-encoded, the decoding method is found, but the problem persists. you can use json_decode ($ _ COOKIE ["userinfo"]) to obtain the original array on the current page, however, after changing the page, the result is "NULL", and the value is read with $ str = cookie ("userinfo"), but the result is:
- Object (stdClass) #4 (3 ){
- ["Name"] => string (6) "zhang san"
- ["Code"] => int (123)
- ["Password"] => string (8) "22334455"
- }
$ Str is a class that is processed as a class.
But I want to get an array, so dump ($ _ COOKIE ["userinfo"]), the result is "{\" name \": \ "\ u5f20 \ u4e09 \", \ "code \": 123, \ "password \": \ "22334455 \"}", that is to say, all escape characters are added, except the numbers. after finding the cause, it is easy to solve the problem. use stripslashes ($ _ COOKIE ["userinfo"]); // after the escape characters are removed, perform the reverse encoding operation json_decode ($ str, true). finally, dump () prints the result and returns the correct array result.
- Array (3 ){
- ["Name"] => string (6) "zhang san"
- ["Code"] => int (123)
- ["Password"] => string (8) "22334455"
- }
The instance code is as follows:
-
- Require_once "ThinkPHP/Common/functions. php ";
- $ User = array (
- "Name" => "James ",
- "Code" => 123,
- "Password" => "22334455 ");
- Cookie (userinfo, $ user, time () + 3600 );
- Var_dump ($ _ COOKIE ["userinfo"]);
- // Re-read as an array
- $ Str = stripslashes ($ _ COOKIE ["userinfo"]); // remove escape characters
- $ Userinfo = json_decode ($ str, true );
- Var_dump ($ userinfo );
- ?>