I am trying to build a PHP Based REST API, but I am stuck with this issue. I have got session_start()
in PHP code and a simple Sign In, Sign Out script, which accepts the same username
and password
to be authenticated:
<?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));
?>
And I am using POSTMan (Chrome Extension) to login and check and everything works fine. But when I use my jQuery's $.getJSON()
and $.post()
methods, when I try action=whoami
, I am just getting Guest
. My jQuery code:
$.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
I have already tried the same thing using POSTMan and it worked charm. But using jQuery this didn't work. So, I tried using:
$.ajaxSetup({
cache: false
});
Nevertheless, I also tried appending a random string like this, but same response:
Not this as well. Can someone please help me proceed? This is a show stopper for me.
$.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