后台php操作cookie
哪个页面访问本php文件,则cookie自动添加到该页面
写入cookie
setcookie('key必要','value必要','expires必要','path可选cookie生效范围(默认存储至当前文件的上一级目录)');
第四个参数path:
'/':域名之下的所有位置都生效
'/code/':在code文件夹范围内生效
读取cookie
$_COOKIE
删除cookie
setcookie('key','value','expires当前时间戳+1','path')
php获取时间戳方式time(),单位是秒
前台文件:
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
</style>
</head>
<body>
<button>点我</button>
<script>
(function(){
console.log(document.cookie);
})();
var btn=document.querySelector('button');
btn.onclick=function(){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if(xhr.readyState==4)
{
if(xhr.status==200)
{
console.log(xhr.responseText);
}
}
}
var data=new FormData();
data.append('uname','jeff');
xhr.open('post','6.php',true);
xhr.send(data);
}
</script>
</body>
</html>
后台文件:
<?php
$uname=$_POST['uname'];
//哪个页面访问本php文件,则cookie自动添加到该页面
//设置
setcookie('uname',$uname,time()+1000);
//删除
setcookie('uname',$uname,time()+1);
//读取
print_r($_COOKIE);
?>