Home  >  Article  >  Backend Development  >  How to solve the garbled problem of php cookies

How to solve the garbled problem of php cookies

藏色散人
藏色散人Original
2021-03-17 09:44:362333browse

php The solution to garbled cookies: First, when writing the Cookie, encode it with Url; then rewrite the Cookie; and finally decode the Url when reading.

How to solve the garbled problem of php cookies

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

php and js when transferring cookies to each other in Chinese The problem of garbled characters

js stores cookies, and when PHP reads them, they become garbled characters.

Problem Analysis:

This is caused by character encoding. Chinese characters have two encodings, so such garbled codes are produced!

Solution:

1: When writing Cookie, first encode it with Url, and then write it

2: When we read it, decode the Url. Can

php two functions

urlencode()

urldecode()

js two Function

decodeURI()

encodeURI()

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 cookies

<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"]);
?>

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to solve the garbled problem of php cookies. 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