Session Time out in PHP or Processmaker - php

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.

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 Session Variables Destroyed Without Instruction For This

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.

How to set lifetime of session

How to set session lifetime in PHP? I Want to set it to forever as long as the request is exist. The request is AJAX. My PHP code that handle AJAX request is:
// AJAX.php
<?php
session_start();
$_SESSION['counter'] = $_SESSION['counter'] + 1;
header('Content-type: application/json');
echo json_encode(array('tick' => $_SESSION['counter']));
?>
and the JavaScript:
$(document).ready(function() {
function check() {
getJSON('ajax.php');
}
function getJSON(url) {
return $.getJSON(
url,
function(data) {
$("#ticker").html(data.tick);
}
);
}
setInterval(function() {
check();
}, 10000); // Tick every 10 seconds
});
The session always resets after 300 seconds.
The sessions on PHP works with a Cookie type session, while on server-side the session information is constantly deleted.
For set the time life in php, you can use the function session_set_cookie_params, before the session_start:
session_set_cookie_params(3600,"/");
session_start();
For ex, 3600 seconds is one hour, for 2 hours 3600*2 = 7200.
But it is session cookie, the browser can expire it by itself, if you want to save large time sessions (like remember login), you need to save the data in the server and a standard cookie in the client side.
You can have a Table "Sessions":
session_id int
session_hash varchar(20)
session_data text
And validating a Cookie, you save the "session id" and the "hash" (for security) on client side, and you can save the session's data on the server side, ex:
On login:
setcookie('sessid', $sessionid, 604800); // One week or seven days
setcookie('sesshash', $sessionhash, 604800); // One week or seven days
// And save the session data:
saveSessionData($sessionid, $sessionhash, serialize($_SESSION)); // saveSessionData is your function
If the user return:
if (isset($_COOKIE['sessid'])) {
if (valide_session($_COOKIE['sessid'], $_COOKIE['sesshash'])) {
$_SESSION = unserialize(get_session_data($_COOKIE['sessid']));
} else {
// Dont validate the hash, possible session falsification
}
}
Obviously, save all session/cookies calls, before sending data.
Set following php parameters to same value in seconds:
session.cookie_lifetime
session.gc_maxlifetime
in php.ini, .htaccess or for example with
ini_set('session.cookie_lifetime', 86400);
ini_set('session.gc_maxlifetime', 86400);
for a day.
Links:
http://www.php.net/manual/en/session.configuration.php
http://www.php.net/manual/en/function.ini-set.php
Prior to PHP 7, the session_start() function did not directly accept any configuration options. Now you can do it this way
<?php
// This sends a persistent cookie that lasts a day.
session_start([
'cookie_lifetime' => 86400,
]);
?>
Reference: https://php.net/manual/en/function.session-start.php#example-5976
Sessions can be configured in your php.ini file or in your .htaccess file. Have a look at the PHP session documentation.
What you basically want to do is look for the line session.cookie_lifetime in php.ini and make it's value is 0 so that the session cookie is valid until the browser is closed. If you can't edit that file, you could add php_value session.cookie_lifetime 0 to your .htaccess file.
Since most sessions are stored in a COOKIE (as per the above comments and solutions) it is important to make sure the COOKIE is flagged as a SECURE one (front C#):
myHttpOnlyCookie.HttpOnly = true;
and/or vie php.ini (default TRUE since php 5.3):
session.cookie_httponly = True
I dont see this mentioned anywhere, but setting ini_set('session.gc_maxlifetime', $max_lifetime); in the PHP file itself is usually not going to have the desired affect if the php.ini file has a LOWER value and the server hosts multiple domains/vhosts. If you have User on X website, and the maxlifetime is set to 10 seconds (not a real value, this is just for example) in the PHP file and then have the maxlifetime set to 5 in php.ini something interesting/unexpected will happen if you have multiple domains/vhosts.
When a 2nd user visits a site that HASNT set ini_set('session.gc_maxlifetime', $max_lifetime); in it's PHP file and it defaults to whatever php.ini has, that will cause PHP's garbage collection to fire using 5 seconds rather than 10 seconds as maxlifetime, thus deleting the user's session which was supposed to last at least 10 seconds.
Therefore, this setting should almost NEVER go in the PHP file itself and should actually be in the vhost entry if your setup has this capability and falls into this type of scenario. The only exception to this is if your server only hosts 1 website/vhost who's PHP files will always override whatever php.ini has.
This happens because all sites use the same tmp dir to store session data. Another mitigation solution would be to set the session tmp dir per vhost. And yet another (not recommended) solution is to simply disable session.cookie_lifetime completely in php.ini by setting it to 0.
As long as the User does not delete their cookies or close their browser, the session should stay in existence.

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.

User Inactivity Logout PHP

I want my users to be logged out automatically after X minutes of inactivity. I also want to have all sessions destroyed.
How can this be done? How can I check for inactivity then perform a function to log them out???
I tired Michiels approach and got no where.
On investigation I saw that the if statement simply added the expiry period to the current time so the statement never fired.
This is my altered version:
set this when logging in user or loading a secure page:
$_SESSION['expire'] = time()+1*60;
And use this to see if the expiry time is less than current time (i.e we're past the expiry limit):
if(time() > $_SESSION['expire']){
$user -> logout();
}
You can set session time out limit like:
ini_set('session.gc_maxlifetime',30);
Here is the possible solution for you.
You could also do:
$_SESSION['loginTime'] = time();
On every page, and when the user is trying to navigate and he has been inactive for an twenty minutes you can log him out like this:
if($_SESSION['loginTime'] < time()+20*60){ logout(); }
Depending on how fast your server is and how many users you have, you can have it send a request to your server whenever a user does anything (navigates, clicks a button, whatever). From this request, update a SQL table with their last activity time.
Have a cron job run through the table at some regular interval and delete the sessions of the users that have been inactive for whatever your threshold is going to be.
If your server is slow or you have a lot of users, you can have this script run infrequently.
PHP's session mechanism already have a garbage collector based on the inactivity timeout. You have no worry about.
You can set the last active time by $_SESSION['lastactive'] = time() and update it every time when user navigates to a new page. Then you can have a function timeout() on every page .
function timeout()
{
$maxtime = 60*2; // Here , maxtime has been set to 2 minutes
if(isset($_SESSION['lastactive']) and (time() - $_SESSION['lastactive'] > $maxtime )) // subtracting current time from lastactive time and seeing if it exceeded timeout limit.
{
signout(); //logging out
}
if(isset($_SESSION['lastactive']) and (time() - $_SESSION['lastactive'] < $maxtime )) // subtracting current time from lastactive time and seeing if it exceeded timeout limit.
{
return 1; // timeout limit not exceeded
}
else
{
if(!isset($_SESSION['lastactive']))
{
$_SESSION['lastactive'] = time(); //if lastactive is not set
}
}
}
Use unset($_SESSION['NAME']); or session_destroy();. You could also change the value of the session.
To do this at a certain time, you would need to set a timestamp in the database, and then call it to check if it's beyond X minutes. Look at the link at the bottom.
I'd personally just use cookies and make them expire at a certain time, but whatever floats your boat.
If current time is more than 30 seconds past time X (from the database)
$(document).ready( function()
{
setTimeout(function() { CALL LOGOUT.PHP VIA AJAX }, 720000);
});
720000 means 12 minutes ( for illustration purpose )
put this script in your header and set ur own time of inactivity
you can set what time u want , it will be work like
if you set 5 minutes then when u login to system then it start count for 5 min. but if u click on any module this script will be reloaded , because when page turns then header is also reload when script is reload then it start count from 0 (initial), but if u cant access the system within 5 min. then it will load the logout.php and system will logs-out
this is how i do it :
//set timeout period in seconds
$idleTime= 60*2;
//check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout'])){
$session_life = time() - $_SESSION['timeout'];
if($session_life > $idleTime){
// your logout code here*
}
}
$_SESSION['timeout'] = time();
This makes $_SESSION['timeout'] reset every time a page is reloaded, i have this in an include file in the header of every sub page, works for me atleast.
The simplest way is this. Send the user to a log out page if they are not activating certain elements on your website
$secondsWait = 300; // these are seconds so it is 300s=5minutes
header("refresh:$secondsWait; logout.php");
contents for the redirect... logout.php, destroy any sessions and maybe also send a message alerting the user why they were logged out
<?php
session_start();
session_unset();
session_destroy();
?>

Categories