我正在尝试构建一个基于PHP的REST API,但我遇到了这个问题。我在PHP代码中得到了session_start()
和一个简单的Sign-in,Sign-Out脚本,它接受相同的username
和password
进行身份验证:
<?php
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json");
$message = array();
if ($_GET["action"] == "signin") {
if (count($_POST) && isset($_POST["username"]) && isset($_POST["password"]) && $_POST["username"] == $_POST["password"]) {
$message["user"] = $_POST["username"];
$message["success"] = true;
$_SESSION["user"] = $message["user"];
} else {
unset($message["user"]);
$message["success"] = false;
unset($_SESSION["user"]);
}
} elseif ($_GET["action"] == "signout") {
session_destroy();
$message["success"] = true;
} elseif ($_GET["action"] == "whoami") {
$message["success"] = true;
$message["user"] = isset($_SESSION["user"]) ? $_SESSION["user"] : "Guest";
}
die(json_encode($message));
?>
我正在使用POSTMan(Chrome扩展)登录和检查,一切都很好。但是当我使用jQuery的$.getJSON()
和$.post()
方法时,当我尝试action=whoami
时,我得到的只是Guest
。我的jQuery代码:
$.getJSON("http://localhost/api.php?action=whoami");
// Gives Guest. Okay! :)
$.post("http://localhost/api.php?action=signin", {
username: "admin", password: "admin"
});
// Gives me success with the user logged in.
$.getJSON("http://localhost/api.php?action=whoami");
// Gives Guest Again! :O
我已经用POSTMan尝试过同样的东西,它很有魅力。但是使用jQuery并没有成功。所以,我尝试使用:
$.ajaxSetup({
cache: false
});
尽管如此,我也尝试添加一个像这样的随机字符串,但相同的响应:
不是这样。有人能帮我继续吗?这对我来说是一场表演。
$.getJSON("http://localhost/api.php?action=whoami");
// Gives Guest. Okay! :)
$.post("http://localhost/api.php?action=signin", {
username: "admin", password: "admin"
});
// Gives me success with the user logged in.
$.getJSON("http://localhost/api.php?action=whoami&kill=cache");
// Gives Guest Again! :O
通常会话存储在Cookie中。因此,当您提出跨域请求时,不会共享Cookie。一个简单的解决方案是使用proxy.php
,但现在我得到了使用命名会话的最佳解决方案。
使用以下代码获取sid
:
<?php
if (isset($_GET["sid"]))
session_id($_GET["sid"]);
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json");
var_dump(session_id()); // Gives you the SID.
从下一次开始,使用sid
作为GET
参数,这将检查服务器会话并恢复会话。