Php Session Variables Destroyed Without Instruction For This - php

I just use Session Variables in my code. I do not start any activity with cookies. I just do session_start() and do the manipulation of the variables.
But at the end of some time (about 30 minutes) the session goes down. If I do print_r ($ _ SESSION) the session is in void.
I've tried set session.gc_maxlifetime to 7200 (2 hours), but the session is destroyed in less than 30 minutes again.
How can I resolve this? It's normal? Should the session not only be destroyed if I close the browser or give the statement/instruction to session_destroy?

The default timeout is 24 minutes.
Other than php.ini, you can change it in code. You could try this:
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
session_start(); // ready to go!
from this answer: How to change the session timeout in PHP?
An article on it:
https://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions
which gives code that I've adapted to 2 hours.
session_start();
$timeout = 7200; // Number of seconds until it times out.
// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
// See if the number of seconds since the last
// visit is larger than the timeout period.
$duration = time() - (int)$_SESSION['timeout'];
if($duration > $timeout) {
// Destroy the session and restart it.
session_destroy();
session_start();
}
}
// Update the timout field with the current time.
$_SESSION['timeout'] = time();
php.net page on it:
http://php.net/manual/en/function.session-set-cookie-params.php
Other stack answers verify this (some highly rated):
PHP sessions default timeout
How do I expire a PHP session after 30 minutes?

Session variables are meant to hold information until the browser is closed. I am not quite sure what you want to achieve in your project, since you have not posted any code.
Something simple like not putting session_write_close(); at the end of your php script or session_start() at the very beginning, before any html tags could be messing your code.

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 login session timeout error

I am creating a login script and when a user logins, he will be able to stay 3 hours before he is logged out by the system.
The following is in my login.php
....
$_SESSION['dgUserLoggedIn'] = true;
$_SESSION['timeout'] = time();
....
the login-check.php which is at the top of every page which needs authentication:
function isLoginSessionExpired() {
$login_session_duration = 10800;
$current_time = time();
if(isset($_SESSION['timeout']) and isset($_SESSION['dgUserLoggedIn'])){
if(((time() - $_SESSION['timeout']) > $login_session_duration)){
session_regenerate_id(true); // change session ID for the current session and invalidate old session ID
$_SESSION['timeout'] = time(); // update creation time
return true;
}
}
return false;
}
if(isset($_SESSION["dgUserLoggedIn"])) {
if(isLoginSessionExpired()) {
header("Location: /core/logout.php");
}
}
With the above code the user logs out automatically after around 30 minutes, how can I make sure the user can stay logged in 3 hours and every page refresh or visiting the time updates itself.
Below is my session-setup.php
// **PREVENTING SESSION HIJACKING**
// Prevents javascript XSS attacks aimed to steal the session ID
ini_set('session.cookie_httponly', 1);
// Adds entropy into the randomization of the session ID, as PHP's random number
// generator has some known flaws
ini_set('session.entropy_file', '/dev/urandom');
// Uses a strong hash
ini_set('session.hash_function', 'whirlpool');
// **PREVENTING SESSION FIXATION**
// Session ID cannot be passed through URLs
ini_set('session.use_only_cookies', 1);
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
// Uses a secure connection (HTTPS) if possible
ini_set('session.cookie_secure', 1);
session_start();
You could also try changing the value at runtime using ini_set:
ini_set('session.gc_maxlifetime', '10800');
or
You can change this line in your php.ini file.
session.gc_maxlifetime = 1440
Update: it seems to be possible, so i stand corrected
php_value
session.gc_maxlifetime = 10800
i hope it will be helpful
Have you checked the value of session.gc_maxlifetime in your php.ini file? I guess this is the one which causes the problem
The sessions default timeout is 24 minutes (1440 seconds).
Please check PHP sessions default timeout
first check default session timeout setting on your server and add the following line in your code. i hope it will work for you
session_set_cookie_params(10800);

Session Time out in PHP or Processmaker

How to do a session time out in php or processmaker(BPM)?
I refered most forum and wikis but that didn't solved my problem.
Please let me know.
On ProcessMaker you have to change the following parameters on your php.ini in order to modify the session time out
session.gc_maxlifetime
session.cache_expire
session.cache_limiter
This will work from version 2.5RC1 (Release Candidate) which is available to be downloaded on the ProcessMaker sourceforge page
Hope this also helps you.
processmaker
Store the last time the user made a request
<?php
$_SESSION['timeout'] = time();
?>
In subsequent request, check how long ago they made their previous request (10 minutes in this example)
<?php
if ($_SESSION['timeout'] + 10 * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
Extracted from here
this are well explained in previous post.
see the link below PHP Session timeout
and
How do I expire a PHP session after 30 minutes?
Include this code in the start of your php scripts:
<?php
if(!isset($_SESSION)){#session_start();}
if (isset($_SESSION['timeout']) and $_SESSION['timeout'] + 1800 < time()) {
session_unset();
session_destroy();
} else {
$_SESSION['timeout'] = time();
}
?>
The first line checks if there is a session, and if there is no session it creates it.
The # sign in front of the session_start() is to suppress any warnings or notices that the session_start() might throw. Nothing important for this code at all, and you can remove it.
The next line checks if the $_SESSION['timeout'] variable exist and if it contains a value more than 30 minutes in to the past from the current time.
The first time you run the script it will not exist, so if you check its value when it does not exist it will give you a notice or warning message if this is enabled in your php.ini file.
If it does not exist we skip to the else and have it created, and we add the current time().
Now the value of 1800 is 30 minutes in seconds. 30 * 60 is another common way to write this to make it easier to read.
If the if is true, the user have been inactive for more than 30 minutes. If it is less than 30 minutes or the first time the script is running, it will skip to the else and update the timeout variable.

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);

how to destroy the session if the application is exceeding more than its given idel time using php

in my program for a security purpose it is neccessary to destroy the session variable if the application exceed more than its idle time.For This i am using this code,
// set timeout period in seconds
$inactive = 300;
// check to see if
$_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
$session_life = time() -
$_SESSION['start']; if($session_life
$inactive)
{ session_destroy(); header("Location: logout.php"); } }
$_SESSION['timeout'] = time();
But this code refresh the session variable every 5 min, i want to know how to destroy the session variable if the system is in the idle time. And also please tell me it create any other problem if i destroy the session variable . Thanks in advance
session_unset
#Edit:
Since the session data are considered garbage after the session timed out, no action should be needed really. It should be sufficient, to make sure, the garbage is cleared in a regular manner. So simply calling a page which creates a dummy session (once a minute fe.) should be enough. The garbage collector frequency may also be configured in php.ini.
However, you can verify this easily by monitoring your sessions (in file / database / memory).
Try this:
Edit php.ini - set session.cookie_lifetime with the intended value in seconds (300 seconds for your 5 minutes).
Restart your apache server.
Login
Test the session variable after 5 minutes (should have expired).
Remember, from the docs:
The default "0" value means that the cookie stays alive until the browser is closed. This is also the default value, if not set in php.ini.
So, you must set it: it defaults to zero - so it will never expire unless someone closes the browser window.

Categories