PHP : Users getting logged out - php

I have a custom written PHP application. Build 15 years ago. Working perfectly fine until recently when users reported they are being logged out even while they are actively using the application.
We use PHP sessions to manage users. The session expiry is set to 12 hours of inactivity. I reproduced the issue of being logged out. There is no pattern. at times I was logged out after 30 mins, at times 2 hours, at times 40 mins and so on. I captured the PHP session cookie and checked that the corresponding PHP session file existed in the tmp directory on the server. The session file was there on the server even when the application got me logged out and it was not even 2 hours (expiry set for 12 hours).
If I print the $_SESSION, this issue does not appear as much. Reproduced the issue in Chrome and Firefox. I have session_start and session_destroy only in logout service.
Any leads what could be causing this?

I faced same problem a few times. Workaround: use a "remember me" cookie for auto login.
Here's a recipe:
Whenever user logins successfully run this:
// remember me for a year every login
$login_string = hash('sha512', $user_id . $_SERVER['HTTP_USER_AGENT'] . time());
Project::update_table_record('users', $user_id, ["remember_me" => $login_string]);
$cookie_name = COOKIE_REMEMBER_ME;
$cookie_value = $login_string;
setcookie($cookie_name, $cookie_value, time() + (86400 * 365), "/"); // 365 day example
Whenever user chooses to logout, give him the option:
setcookie(COOKIE_REMEMBER_ME, "", time() - 3600, "/");
Otherwise, if no session then re-login if cookie is valid.
// auto login / remember me!
if (!LiveUser::get_id()) {
if (isset($_COOKIE[COOKIE_REMEMBER_ME])) {
$user_string = $_COOKIE[COOKIE_REMEMBER_ME];
$user_id = Project::get_value('users', ['remember_me' => $user_string], 'id');
if ($user_id) {
Project::do_login($user_id);
}
}
}

Related

How to increase login session timeout?

Question:
How to increase login session timeout?
Situation:
I have a login script in PHP that connects to a MYSQL database. Right now a login session lasts for about 24 hours. But I want this to be 2 weeks. So I want my users to have to login again after 2 weeks. Again, right now a user has to re-login after about 24 hours. I haven't been able to measure this precisely. But I always have to re-login the next day. What I also should mention is that I have closed the browser and even restarted the computer to see if I'm still logged in the same day. And yes, the login session is still intact. But the next day this session is gone.
Code used but did not work:
ini_set('session.gc_maxlifetime', 1209600);
session_set_cookie_params(1209600);
session_start();
I noticed when looking at my php.ini file that mysqlnd read timeout lasts for exactly 24 hours. So I also added the following code to the code above:
ini_set('mysqlnd.net_read_timeout', 1209600);
But this all doesn't make any difference. I also tried the following code that I found on codeleaks.io. I added the following code in my login script:
session_start();
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (60);
And the following code on my landing page after logging in:
$currentTime = time();
if($currentTime > $_SESSION['expire']) {
session_unset();
session_destroy();
}
I set 60 seconds just to see if it works. And indeed, this works. Session will expire after 60 seconds. But when I want this session to last more than 24 hours then it doesn't work. So something else is destroying the session. I can't figure out what it is. I hope one of you guys can help me. Please note that I'm just an amateur.
To increase the login session timeout in PHP, you can use the session_set_cookie_params() function to set the lifetime of the session cookie. This function takes two parameters: the lifetime of the cookie in seconds, and the path on the server in which the cookie will be available. For example, to set the session timeout to 2 hours, you can use the following code:
$lifetime = 7200;
session_set_cookie_params($lifetime);
session_start();
This will set the session cookie to expire after 2 hours (7200 seconds) of inactivity.
Alternatively, you can also set the session timeout using ini_set() function
ini_set('session.gc_maxlifetime', 7200);
session_start();
Please note that you need to call session_start() after setting the parameters to take effect

PHP setcookie has stopped working with no code change

I know this question gets asked a million times but this one is very different. This code has worked flawlessly for over 3 years but now has stopped working.
The cookie in question holds a members id for an 'auto login' when returning to the site. The cookie is set via a jQuery call to a function upon log in. Once they are logged in the function returns a value and the calling script redirects the member to their control panel:
if (strlen(trim($_POST['keep_logged'])) != 0) {
if(setcookie('foacmemberinformation', $row['member_id'], time() + 60 * 60 * 24 * 365, '/')) {
error_log('in set cookie line 68');
}
else {
error_log('set cookie failed');
}
}
I just added the if else statement around the set cookie to verify that the set cookie function is returning true.
What seems to be causing it is when a member uses the 'log out' function on the site which is as simple as this:
session_start();
session_destroy();
setcookie('foacmemberinformation', '', time() - 3600);
header('Location: /Member-Login');
Now I personally have used this log out, then log back in and remember function hundreds if not thousands of times over the past three year and have never had an issue until now. It also is happening in all browsers.
I have verified that setcookie is returning true and there is no output before except another cookie (setcookie('foacmemberstate', $row['state'], time() + 60 * 60 * 24 * 14, '/');) which IS being set. I even commented that set cookie out and tried and still the 'problem' cookie is not setting.
I don't get what is happening after it worked for 3 years!

php cookie not setting after logging out

I'm making a website where some users can log in. I have my code create a simple cookie. Earlier my code was working and creating a cookie and allowing users to sign in. However, after I created a log out button and used it, I couldn't seem to create a cookie again (my website doesn't recognize a cookie and no cookie shows up in chrome when I check). I've already looked at all the other threads about creating a cookie and not being able to create a cookie, but I can't figure out what is wrong.
Here is my code to create a cookie:
$userStuff = array('name' => $username,'password' => $password);
$date_of_expiry = time() + 60 * 60 * 24 * 1 ;
setcookie( "user", $userStuff, $date_of_expiry, "/" ) ;
I know that the security is extremely lax and that I shouldn't store the password and such directly in a cookie, but I want to work on other things first. This code is before any html.
Here is my code where I changed the expiration date of the cookie to log out:
setcookie('user', $userStuff, time() - 3600, '/');
how are you?
If you want to delete a cookie, you should pass a date in the past, for example:
setcookie('user', $userStaff, time() - 3600, '/');
Regards.
I know this is a bit aside the point, but why not use $_SESSION? It stores a cookie with a session token in your client's browser (when you run session_start) and most of the data is stored server side which is far more secure. For user auth data and tokens this is probably a better choice.
Example:
//First thing init the session
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
//Or retreive the data...
$username = $_SESSION['username'];
//Later when you want to log out just destroy the session:
session_destroy();
I found the error. Apparently, you either cannot use arrays in cookies, or it just wouldn't let me use an array in my cookie this time.

PHP: pop show that app server time out

I have a PHP app written in codeIgniter. Getting some complaints from clients about the app timing out. Their session times out after two hours of inactivity and they can't seem to remember that.
Is there a way and if so, how, to show a pop up message when a users session has timed out?
Thank you in advance.
PHP cannot display a pop up by itself, but you could probably have a JavaScript query the session status and display a pop up when the session is expired, or even better, count the time since the session opened and let the user know in advance that his session is about to time out
If you want change the duration of the session, see this line in your config.php
$config['sess_expiration'] = 7200;
7200 is 120 minutes * 60 seconds. If you change it to 0, the session will not expire.
To add a warning, the very simplest method would probably to add a JavaScript similar to
setTimeout(function(){alert("Your session will expire in 5 minutes")},6900000); // 6900 seconds (115 minutes) * 1000 milliseconds
You could do it using:
Javascript function using timers (and show a popup after a period of time)
In PHP using a timer set in your $_SESSION and calculate the difference in timestamps (when the user is redirected to a login page, pass a message "Your session has timed out")
A hard-timeout/page redirect using a meta equiv tag to a session-timeout page.
You can even go as far as offering different timeout periods for different user groups...
An example using PHP, which logs them out, tells them and redirects once they log back in:
// get time now
$now = time();
// Set session period
$autologout = '7200';
if (isset($_SESSION["TimeOut"]))
{
if ($now > $_SESSION["TimeOut"])
{
// Unregister session and set message
session_unregister("authenticatedUser");
session_register("loginMessage");
$loginMessage = "Your session has timed out";
// Capture request URL and store in a cookie so that they
// are logged back into the page they were requesting
$requestURL = $_SERVER[REQUEST_URI];
setcookie("requestURL",$requestURL,"0",'/','',FALSE,TRUE);
// Redirect back to login page
header("Location: " . $loginScript);
exit;
} else {
$_SESSION['TimeOut'] = ($now + $autologout);
}
} else {
$_SESSION['TimeOut'] = ($now + $autologout);
}
This presumes that your system session timeouts are longer or set otherwise. It's not written for codeIgnitor either, but hopefully helpful to understand what can be done to soften the blow of session expiry.
Probarly your session maxlifetime is 2 hours.
You can edit that with this: (replace 8 with the max lifetime in hours).
ini_set(’session.gc_maxlifetime’, 8*60*60);

What is the code for Stay logged in or Remember me while user login in PHP

I don't know how to write php code for Stay logged in or remember me while user check the option while login. I want to stay user logged in at least 60min until user close the browser. What is the code for this in PHP.
If you are using session.
These threads will help you:
Stay logged in & remember me - PHP sessions and cookies
how to logout session if user idle in php
You can use session_set_cookie_params to set specific time of session life.
if you are using session, this would probably help
function lifetime(){
$inactive = 3600; //60 minutes, i suppose in seconds
if(isset($_SESSION['start']) ) {
$session_life = time() - $_SESSION['start'];
if($session_life > $inactive){
//your log out code
}
}
$_SESSION['start'] = time();
}
http://www.tizag.com/phpT/phpsessions.php This should be helpful
You should use cookies for this:
cookies

Categories