Home > Article > Backend Development > How to solve the garbled problem of php cookies
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.
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('; '); for (var i=0; i < aCookie.length; i++) { var aCrumb = aCookie[i].split('='); if (sName == aCrumb[0]) return decodeURI(aCrumb[1]); } return ''; } </script>
js sets cookie PHP reads cookies
<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"]); ?>
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!