Home >Backend Development >PHP Tutorial >Reasons and solutions for Chinese garbled characters when php and js transfer cookies to each other

Reasons and solutions for Chinese garbled characters when php and js transfer cookies to each other

零到壹度
零到壹度Original
2018-04-11 16:59:532014browse

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 sets cookie, js reads cookie


<?php
setcookie ("TestCookie", urlencode("这就是网页21"));
?>
<script type="text/javascript">
    alert(decodeURI(getCookie("TestCookie")))    
    function getCookie(sName) {    
    var aCookie = document.cookie.split(&#39;; &#39;);    
    for (var i=0; i < aCookie.length; i++) {    
    var aCrumb = aCookie[i].split(&#39;=&#39;);    
    if (sName == aCrumb[0])    
    return decodeURI(aCrumb[1]);
 } return &#39;&#39;;
}
</script>

js sets cookie php reads cookie
<script type="text/javascript">function setCookie(name, value, time){    
        var nameString = name + &#39;=&#39; + 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 = &#39; ;expires = &#39;+ 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn