Reputation: 416
I have built a php backend library, for a ios app of mine, and I am using sessions to know if the user is logged in. But for some reason, even after setting the session variable, when I try to retrieve it, it is retrieved as undefined, making my app think the user isn't logged in, even though the user is logged in. Is there any alternative for using sessions, or did I setup my session wrong? Here is the code:
Login call:
session_start();
// Login stuff
$_SESSION["id"] = /* My id, which isn't undefined */;
Checking whether user is logged in or not:
session_start();
if (isset($_SESSION["id"])) {
$id = isset($_SESSION["id"]);
echo $id;
// do stuff
}
else {
echo "You are not logged in.";
// user not logged in
// This condition is always called, and I am not able to change it no matter what I do.
}
Upvotes: 0
Views: 222
Reputation: 1969
Just do
// On the first page
session_start(); // Login stuff
$user_id = 2; //or something from the database or via authentication.
$_SESSION["id"] = $user_id; /* My id, which isn't undefined */;
On the target page;
session_start();
if(isset($_SESSION["id"])){
$id = $_SESSION["id"];
echo " session id is set do your processing here.";
}else{
echo "session id is not set";
}
Upvotes: 0
Reputation: 416
I ended up not relying on cookies or tokens, and using the database. The user is logged out after half an hour. I modified my users table in mysql, and added 2 new columns, loggedIn
as a boolean
, and lastLoggedIn
as a timestamp
. From there, I checked if it has been half an hour after logging in, if yes, change the loggedIn to false, or else, the user is logged in.
Upvotes: 1
Reputation: 61784
EDIT: This answer refers to the code originally posted, which has since been edited by the OP.
if ($id = $_SESSION["id"]) {
should be
if ($id == $_SESSION["id"]) {
i.e. ==
not =
.
A single equals will set the value of the left-hand variable, and the result, assuming that $_SESSION["id"]
is actually set will always evaluate to true
. If $_SESSION["id"]
is null or not set, then the expression will always evaluate to false
.
A double equals compares the two variables.
However, a more conventional solution would simply be:
if (isset($_SESSION["id"])) {
Upvotes: 1
Reputation: 666
Ajax request wont save the session cookie by it's own, You may wanna use JWT tokens
Take a look at this JWT tutorial
Upvotes: 1