PHP and JS Mutual-transmitted cookies cause Chinese garbled characters and solutions

Source: Internet
Author: User
Tags setcookie urlencode
This article to share the content is PHP and JS Mutual transmission of cookies caused by the Chinese garbled reasons and solutions, has a certain reference value, the need for friends can refer to

Problem Analysis:

This is because of the text encoding, the Chinese character is two code, so it will be made out of such garbled!

Solution Ideas:

1: When a cookie is written, it is encoded with a URL and then written

2: When we read the URL decoding can be

PHP two functions

UrlEncode ()

UrlDecode ()

JS two functions

decodeURI ()

encodeURI ()

5.5 Previous version is escape unescape

PHP settings cookie, JS read cookie


<?phpsetcookie ("TestCookie", UrlEncode ("This is Page 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 Settings cookie PHP Read cookie

<script type= "Text/javascript" >function Setcookie (name, value, time) {            var namestring = name + ' = ' + encodeURI (v Alue);            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 = ";p ath =/"; document.cookie = namestring + expirystring + path;} Setcookie ("Testjscookie", "I am Chinese", 0)  </script>


<?phpecho UrlDecode ($_cookie["Testjscookie"]);? >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.