【发布时间】:2017-06-30 16:58:30
【问题描述】:
标题说明了一切,我无法弄清楚为什么我无法从同一域上的两个不同服务器获取或设置 cookie。将$path 设置为/,$domain 指定为127.0.0.1,$secure 设置为false,$httponly 设置为false。
下面是更详细的情况:
服务器 1 - 127.0.0.1
在
Server 1我有一个PHP 脚本,如果设置了cookie,它会获取一个cookie,然后设置一个新的cookie。然后将新旧 cookie 值作为 JSON 返回。
服务器 2 - 127.0.0.1:8000
在具有相同域名但端口不同的
Server 2上,我有一个HTML 文件从Server 1请求脚本。我无法获取 cookie,或从Server 2设置一个新的。
这里是文件:
Server 1上的 PHP 脚本
<?php
header ('Access-Control-Allow-Origin: *');
$old = !empty ($_COOKIE['test']) ? $_COOKIE['test'] : 'none';
$new = rand (0, 1000);
setcookie ('test', $new, time () * 2, '/', '127.0.0.1', false, false);
echo json_encode ('old: ' . $old . ' new: '. $new);
Server 2上的 HTML 文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
var test = new XMLHttpRequest ();
test.onreadystatechange = function ()
{
if (this.readyState !== 4 || this.status !== 200) {
return;
}
document.body.innerHTML = JSON.parse (this.responseText);
};
test.open ('POST', 'http://127.0.0.1/cookieget.php', true);
test.send ();
</script>
</head>
<body></body>
</html>
“这到底是怎么回事?!”
【问题讨论】:
标签: javascript php ajax cookies cors