to begin I'd like to explain what I'm trying to accomplish.
So I have a system where if a user logs in, their username gets stored in $_SESSION['username']
. On each page I have session_start();
and I then often check to see if(isset($_SESSION['username']))
to show different things.
This all works great, except for the fact that either the session expires before the timeout, or the $_SESSION['username']
variable gets unset before the timeout, causing the system to think that the user needs to be logged out. I would really like to add that this happens at random!
I can spend 10 minutes on the website with different intervals between interaction and nothing happens, next thing I know, I get kicked out twice in 3 minutes.
I can verify that session.cookie_lifetime = 0
(Which means that it won't expire until the browser closes) and that session.gc_maxlifetime = 1200
(Which doesn't matter, as I have set my session save folder in a different location than tmp).
The only thing I can think of that might be an issue is this code in the login section once the password has been verified:
$_SESSION['username'] = $usernameInput;
session_write_close();
header("Location: index.php");
I know that using header means the session variables do not get saved, as it cuts of the document, but that is why I use session_write_close();
to save these variables. And please keep in mind: Everything works after this! I can see my username once I get to index.php.
There are some SO threads that result in the user saving session variables and stuff on a database, but I'd rather fix it without having to do that.
EDIT:
So I reintroduced a function to count timeout for sessions and that works, but I have made a discovery. I've looked into the network
section of the browser and in XHR
I look for the sessions and the cookies and stuff. Something weird happens where the website does a GET request to my logout.php
file.
So I looked at what could cause this. I have 2 logout buttons that get echo'd by PHP and I gave them each different href links. I narrowed it down to this PHP and HTML. Last time I checked, HTML doesn't automatically go to href's in it's code. And I doubt PHP does this.
if(isset($_SESSION['username'])){
echo "<div class='navProfile navButton'><img class='navProfileIcon' src='images/angerypigeon.jpg' alt=''><h3 class='navProfileUsername'>" . $_SESSION['username'] . "</h3><h3 class='navProfilePosts'>Posts: 102</h3><a class='navProfileLogout' href='php_tools/logoutbutton2.php'>Logout</a></div>";
echo "<button class=\"modalButton upload navButton\" id=\"uploadButton2\" type=\"button\" name=\"button\" style=\"margin-left: auto\">Upload</button>";
}
else {
echo "<button class='navButton' type=\"button\" name=\"button\" onclick=\"location.href = 'login.php'\">Login</button>";
}
When I check my XHR fields in the browser, it sends a GET request for logoutbutton2
.
How can I prevent this from happening? I am not clicking on the button myself. It gets sent randomly.