Home >Backend Development >PHP Tutorial >How PHP reads cookies set by JavaScript

How PHP reads cookies set by JavaScript

不言
不言Original
2018-06-04 17:34:291372browse

This article mainly introduces how PHP reads Cookies set by JavaScript. Has very good reference value.

Cookies are used a lot in development, but what if you use JavaScript to set the cookie and then use PHP to read it out? 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 cookies set by PHP without any obstacles. No need to 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 How PHP reads cookies set by JavaScript. 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