php读取JS写入的COOKIE,怎么读取
推荐于2016-09-23
展开全部
<!DOCTYPE script PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
header("content-type:text/html; charset=utf-8");
//在PHP中设置COOKIE
setcookie("phpCookie","我是PHP产生的Cookie", time()+3600);
?>
<script language="javascript">
//JavaScript中设定Cookie值
function setCookie(name,value)
{
var Days = 1/1440; //此 cookie 将被保存 30 天
var exp = new Date(); //new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
//JS取JS保存的cookie
function getCookie2(name)
{ var temp = name + "=";
var tempLen = temp.length;
var cookieLen = document.cookie.length;
var i = 0;
while (i < cookieLen) {
var j = i + tempLen;
if (document.cookie.substring(i, j) == temp) {
return getCookieVal(j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
//辅助
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) {
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
}
//js取PHP保存的Cookie值
function getCookie(sName)
{
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++){
var aCrumb = aCookie[i].split("=");
if (encodeURIComponent(sName) == aCrumb[0])
return decodeURIComponent(aCrumb[1]);
}
return null;
}
</script>
<script>
//显示经过解码的PHP设置的COOKIE
alert(getCookie("phpCookie"));
//使用JavaScript设置COOKIE值
setCookie("jsCookie","我是JavaScript产生的Cookie");
alert(getCookie2("jsCookie"));
</script>
<?php
//显示JavaScript设置的COOKIE的
if (isset($_COOKIE["jsCookie"]))
echo urldecode($_COOKIE["jsCookie"]);
echo "<br />";
echo $_COOKIE["phpCookie"];
?>
</body></html>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询