Home > Article > Backend Development > Detailed example of how PHP reads cookies set by JavaScript
This article mainly introduces the PHP method of reading the Cookie set by JavaScript. Has very good reference value. Let’s take a look with the editor below
Cookies are used a lot in development, but how to implement it if you use Javascript to set cookies and then use PHP to read them? That is, is it feasible to use cookies interactively under PHP and Javascript?
<?php // 读取Javascript设置的cookie header("Content-type: text/html; charset=utf-8"); if(isset($_COOKIE["param"])){ echo $_COOKIE["param"]; } ?> <script type="text/javascript"> function $_cookie(name,value){ var date = new Date(); $livetime = 5*24*3600*1000;// cookie生命周期 date.setTime(date.getTime()+$livetime); document.cookie = name+"="+value+";expires="+date.toGMTString(); } // 设置cookie $_cookie("param","javascript设置cookie"); </script>
The above code has been tested and passed. Of course, this is just the simplest implementation. For more complete functions, please modify it according to your own needs.
A few points to note:
#1. PHP uses its own function to read the cookie set by PHP without any obstacles. Decoding processing.
2. js uses the cookie.js method to read the cookies set by js without any obstacles and without decoding.
3. When js reads the Chinese cookies of PHP, it is recommended to use the decodeURIComponent (escape("...")) function, otherwise the reading may not be normal
4. When PHP reads Chinese cookies from JS, it is recommended to do unescape processing, otherwise garbled characters may appear.
The above is the detailed content of Detailed example of how PHP reads cookies set by JavaScript. For more information, please follow other related articles on the PHP Chinese website!