The content of this article is to share with you the reasons and solutions for Chinese garbled characters caused by the mutual transfer of cookies between php and js. It has a certain reference value. Friends in need can refer to it
Problem analysis:
#This is caused by character encoding. Chinese characters have two encodings, so it is Such a garbled code came out!
Solution:
1: When writing a cookie, first use it Url encoding, and then write it
2: When we read it, we can decode the Url
php two functions
urlencode()
urldecode()
js two functions
##decodeURI()
encodeURI()
The version before 5.5 is escape unescape
<?php setcookie ("TestCookie", urlencode("这就是网页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>
<script type="text/javascript">function setCookie(name, value, time){ var nameString = name + '=' + encodeURI(value); 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 = " ;path =/"; document.cookie = nameString + expiryString + path; }setCookie("TestJsCookie", "我是中国人", 0) </script>
<?php echo urldecode($_COOKIE["TestJsCookie"]); ?>
The above is the detailed content of Reasons and solutions for Chinese garbled characters when php and js transfer cookies to each other. For more information, please follow other related articles on the PHP Chinese website!