This article to share the content is PHP and JS Mutual transmission of cookies caused by the Chinese garbled reasons and solutions, has a certain reference value, the need for friends can refer to
Problem Analysis:
This is because of the text encoding, the Chinese character is two code, so it will be made out of such garbled!
Solution Ideas:
1: When a cookie is written, it is encoded with a URL and then written
2: When we read the URL decoding can be
PHP two functions
UrlEncode ()
UrlDecode ()
JS two functions
decodeURI ()
encodeURI ()
5.5 Previous version is escape unescape
PHP settings cookie, JS read cookie
<?phpsetcookie ("TestCookie", UrlEncode ("This is Page 21"));? >
<script type= "Text/javascript" > alert (decodeURI (GetCookie ("TestCookie")) function GetCookie (sName ) { var acookie = Document.cookie.split ('; '); for (var i=0; i < acookie.length; i++) { var acrumb = acookie[i].split (' = '); if (SName = = acrumb[0]) return decodeURI (Acrumb[1]);} return ';} </script>
JS Settings cookie PHP Read cookie
<script type= "Text/javascript" >function Setcookie (name, value, time) { var namestring = name + ' = ' + encodeURI (v Alue); var expirystring = ""; if (time!== 0) { var expdate = new Date (); if (time = = NULL | | IsNaN (TIME)) time = 60*60*1000; Expdate.settime (Expdate.gettime () + time ); expirystring = '; expires = ' + expdate.togmtstring (); } var path = ";p ath =/"; document.cookie = namestring + expirystring + path;} Setcookie ("Testjscookie", "I am Chinese", 0) </script>
<?phpecho UrlDecode ($_cookie["Testjscookie"]);? >