search
HomeBackend DevelopmentPHP TutorialOne minute to understand the mutual reading of js and PHP settings cookies (with code)

This article will share with you a one-minute interpretation of the mutual reading of js and PHP cookies (with code attached). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

One minute to understand the mutual reading of js and PHP settings cookies (with code)

PHP与JavaScript下Cookie的交互使用
下面的例子列出几种情形交互场景,列出JS和php交互的方法。总结下,以免日后再为cookie问题困扰。
setcookie.php


<?php
    setcookie(&#39;php_cn_ck&#39;,&#39;php_中文_cookie&#39;);
setcookie(&#39;php_en_ck&#39;,&#39;php_english_cookie&#39;);
?>
<script src="cookie.js"></script>
<script>
    Cookies.set(&#39;js_cn_ck&#39;,&#39;js_中文_cookie&#39;,5000);
 Cookies.set(&#39;js_en_ck&#39;,&#39;js_english_cookie&#39;);
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
PHP cookie已经设置<br>php_cn_ck=php_中文_cookie<br>php_en_ck=php_english_cookie<br><br>
JS cookie已经设置<br>js_cn_ck=js_中文_cookie<br>js_en_ck=js_english_cookie<br><br>
<a href=getcookie.php>读取cookie</a><br>
getcookie.php
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
一 读取php传送的中英文cookie<br><br>
<p>1 php读取php设置php cookie<br><br>
<?php
include(&#39;function.php&#39;);
 $php_cn_ck=$_COOKIE[&#39;php_cn_ck&#39;];
  $un_php_cn_ck=unescape($php_cn_ck);
    echo "解码前的中文cookie:php_cn_ck=$php_cn_ck<br><br>";
    echo "解码后的中文cookie:un_php_cn_ck=$un_php_cn_ck<br><br>";
10        $php_en_ck=$_COOKIE[&#39;php_en_ck&#39;];    
11       echo "英文cookie无需解码:php_en_ck=$php_en_ck<br><br>";    
12    ?>    
13    <p>2 js读取php设置cookie<br><br>    
14    <script src="cookie.js"></script>    
15    <script>    
16        php_cn_ck=Cookies.get(&#39;php_cn_ck&#39;);    
17        un_php_cn_ck = decodeURIComponent (escape(php_cn_ck));    
18       document.write("解码前的中文cookie :php_cn_ck="+php_cn_ck+"<Br><br>");    
19        document.write("解码后的中文cookie :un_php_cn_ck="+un_php_cn_ck+"<Br><br>");    
20        php_en_ck=Cookies.get(&#39;php_en_ck&#39;);    
21      document.write("英文cookie无需解码 :php_en_ck="+php_en_ck+"<Br><br>");    
22    </script>    
23    -----------------------------------------------<br>    
24    二 读取JS传送的中英文cookie<br><br>    
25    <p>1 php读取JS设置js cookie<br><br>    
26    <?php    
27        $js_cn_ck=$_COOKIE[&#39;js_cn_ck&#39;];    
28      $un_js_cn_ck=unescape($js_cn_ck);    
29      echo "解码前的中文cookie:js_cn_ck=$js_cn_ck<br><br>";    
30        echo "解码后的中文cookie:un_js_cn_ck=$un_js_cn_ck<br><br>";    
31        $js_en_ck=$_COOKIE[&#39;js_en_ck&#39;];    
32        echo "英文cookie无需解码:js_en_ck=$js_en_ck<br><br>";    
33    ?>    
34    </p>    
35    <p>2 js读取js设置的cookie<br><br>    
36    <script>    
37        js_cn_ck=Cookies.get(&#39;js_cn_ck&#39;);    
38        document.write("解码前的中文cookie :js_cn_ck="+js_cn_ck+"<Br><br>");    
39        //un_js_cn_ck = decodeURIComponent (escape(js_cn_ck)); 调用这两句会出现js解析中断    
40        //document.write("解码后的中文cookie :un_js_cn_ck="+un_js_cn_ck+"<Br><br>");    
41        js_en_ck=Cookies.get(&#39;js_en_ck&#39;);    
42        document.write("英文cookie无需解码 :js_en_ck="+js_en_ck+"<Br><br>");    
43    </script>    
44    </p>    
总结:

php用自身函数读取php 的cookie,没有任何障碍,无需解码处理。
js采用cookie.js方法读取js 的cookie,没有任何障碍,无需解码处理。
js读取php的中文cookie,需要做 "decodeURIComponent (escape(php_cn_ck)) "函数处理
php读取js的中文cookie 需要做 "unescape()" 函数处理


cookie.js
view source
print
    ?
01        var Cookies = {};    
02        /**    
03        * 设置Cookies    
04        */    
05        Cookies.set = function(name, value){    
06            var argv = arguments;    
07            var argc = arguments.length;    
08            var expires = (argc > 2) ? argv[2] : null;    
09            if(expires != null){    
10                var exp   = new Date();    
11                exp.setTime(exp.getTime() + 8*3600 + expires);    
12            }    
13            alert(exp.toGMTString());    
14            var path = (argc > 3) ? argv[3] : &#39;/&#39;;    
15            var domain = (argc > 4) ? argv[4] : null;    
16            var secure = (argc > 5) ? argv[5] : false;    
17            document.cookie = name + "=" + escape (value) +    
18            ((expires == null) ? "" : ("; expires=" + exp.toGMTString())) +    
19            ((path == null) ? "" : ("; path=" + path)) +    
20            ((domain == null) ? "" : ("; domain=" + domain)) +    
21            ((secure == true) ? "; secure" : "");    
22        };    
23        /**    
24        * 读取Cookies    
25        */    
26        Cookies.get = function(name){    
27            var arg = name + "=";    
28            var alen = arg.length;    
29            var clen = document.cookie.length;    
30            var i = 0;    
31            var j = 0;    
32            while(i < clen){    
33                j = i + alen;    
34                if (document.cookie.substring(i, j) == arg)    
35                    return Cookies.getCookieVal(j);    
36                i = document.cookie.indexOf(" ", i) + 1;    
37                if(i == 0)    
38                    break;    
39            }    
40            return null;    
41        };    
42        /**    
43        * 清除Cookies    
44        */    
45        Cookies.clear = function(name) {    
46            if(Cookies.get(name)){    
47            var expdate = new Date();     
48            expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));     
49            Cookies.set(name, "", expdate);     
50        }    
51    };    
52        Cookies.getCookieVal = function(offset){    
53            var endstr = document.cookie.indexOf(";", offset);    
54            if(endstr == -1){    
55                endstr = document.cookie.length;    
56            }    
57            return unescape(document.cookie.substring(offset, endstr));    
58        };

Recommended study: "PHP Video Tutorial"

The above is the detailed content of One minute to understand the mutual reading of js and PHP settings cookies (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

HTTP Method Verification in LaravelHTTP Method Verification in LaravelMar 05, 2025 pm 04:14 PM

Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method() and isMethod() methods efficiently identify and validate request types. This feature is crucial for building

Discover File Downloads in Laravel with Storage::downloadDiscover File Downloads in Laravel with Storage::downloadMar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!