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

零到壹度
Release: 2023-03-23 15:50:02
Original
1949 people have browsed it

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"));
?>
Copy after login
<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>
Copy after login

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>
Copy after login


<?php
echo urldecode($_COOKIE["TestJsCookie"]);
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!