Solution to the garbled code when JS reads Chinese cookies set in PHP: 1. First use the escape function to encode in PHP, and use unescape decoding in js when reaching the client; 2. Use [setrawcookie( )] function to replace the cookie value.
Solution to the garbled code when JS reads the Chinese cookie set in PHP:
In PHP first Use the escape function to encode, and use unescape decoding in js when reaching the client.
The escape function is as follows:
function escape($str) { preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$str,$r); $ar = $r[0]; foreach($ar as $k=>$v) { if(ord($v[0]) < 128) $ar[$k] = rawurlencode($v); else $ar[$k] = "%u".bin2hex(iconv("GB2312","UCS-2",$v)); } return join("",$ar); }
Example:test.php
$v) { if(ord($v[0]) < 128) $ar[$k] = rawurlencode($v); else $ar[$k] = "%u".bin2hex(iconv("GB2312","UCS-2",$v)); } return join("",$ar); } $name = escape("深圳人"); setcookie("name", $name); ?>function get_cookie(name) { var result = null; var myCookie = document.cookie + ";"; var searchName = name + "="; var startOfCookie = myCookie.indexOf(searchName); var endOfCookie; if (startOfCookie != -1) { startOfCookie += searchName.length; endOfCookie = myCookie.indexOf(";",startOfCookie); result = unescape(myCookie.substring(startOfCookie, endOfCookie)); } return result; } document.write("js:" + unescape(getCookie("name")));
There is also another method:
In PHP5 , you can use thesetrawcookie()
function instead. It is not encoded when setting the cookie value, so there is no need to use the escape function to encode it when setting the cookie. At this time, JS can also read it directly. The value of cookie
Related learning recommendations:PHP programming from entry to proficiency
The above is the detailed content of What should I do if garbled characters appear when JS reads the Chinese cookies set in PHP?. For more information, please follow other related articles on the PHP Chinese website!