How to set session life time - php

Is there any way to set the life time on a specific session. For
example let's say that I have 2 session:
$_SESSION['A']='1'
$_SESSION['B']='2'
I want, for example, change the life time on the session A, on 60s. Could I do this without using cookies (For avoid user manipulation)?

you could do like this to control particular session
$_SESSION['first_session']="10";
$now = time();
if (isset($_SESSION['destroy_session']) && $now > $_SESSION['destroy_session']) {
session_unset($_SESSION['first_session']);
}
$_SESSION['destroy_session'] = $now + 10; //10 secs
echo $_SESSION['first_session'];
after 10 seconds your session will get empty.

Server side information should constantly deleted.
For set life time session in php, you can use the function session_set_cookie_params, before the session_start.
session_set_cookie_params(3600,"/");
session_start();

Related

Logout a user after certain time

I'm currently storing a timestamp of the users last activity in my database in which if that hasn't been updated for 15 minutes (for testing doing 2 minutes) I want it to log the user out.
I have been trying different things but they all seem to log me out even though they shouldn't be.
Example of something I've tried
$Online = time() - 120;
if ($CheckOnline['lastaction'] < $Online){
header("Location: Logout.php");
session_destroy();
}
Am I going at this the wrong way.? If I do $Online < $CheckOnline['lastaction'] it keeps me logged in but never logs me out.
Thank you in advance!
Supposing the 'lastaction' is in epoch time format, this would be quite easy. You can check by the current time minus the last action time, that will give you the time in-between the actions. You can do something like this:
$maxTimeAllowed = 120; // 2 Mins
if ((time() - $CheckOnline['lastaction']) > $maxTimeAllowed){
session_start();
session_destroy();
header("Location: Logout.php");
}
I should also mention, in order for you to destory a session you must start it first, but I figure you would handle that logic either in your logout.php or on the page this will be run on, but i've included it just incase.
Another alternative is via javascript.
setTimeout(() => {
window.location = 'logout.php'
}, 120000) // 120000 because JS counts in milliseconds
That way, this will ensure that no matter what the user will be logged out in 2m, not just when they make another request.
Sidenote: If the date/time in your database is stored not as epoch time, it might be worth using strtotime() to convert them, as epoch time is much easier to work with.

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.

Protect download path with PHP Sessions/Cookies?

I need to ensure that a person has been to, and filled out, a registration form before going to the product download page. Right now I submit the form via ajax and if the returned JSON = success I redirect to the appropriate download page accordingly. I would like to protect the download page from direct access, to ensure we capture the lead first. I know that PHP sessions and cookies can be manipulated but it fits our needs, I am aware of the consequences etc and just need to make this work.
So on page 'http://www.example/register.php' I want to set and hash a cookie based on the current time:
<php
$time = ('Y-m-d H:i:s');
//set a new cookie with this value and hash it
?>
Then on http://www.example.com/download.php check for the cookie, if it is set AND set within the last hour display the download content, if it isn't set or has expired, redirect back to the register page
<php
if !$cookie or expred {
location('http://www.example.com/register.php');
die();
} else {
//download content
}
?>
I know this example is very rudementary, but I could use some help getting on the right path. I apprecite it!
You will need to use session_start() at the top of each page, without this you cannot read or write any session data.
Once you have done this, you will change session variables in the $_SESSION global. To set the time try $_SESSION['time'] = time(). This will save the current time in seconds (Unix Timestamp). To calculate if the time was set greater than an hour ago use this:
session_start();
// 60 seconds * 60 minutes = 3600, or 3600 = seconds in an hour
if(time() - $_SESSION['time'] > 3600) {
// Current time - survey_time is greater than one hour (expired)
header('Location: /survey/page/url/');
} else {
// Not expired - do stuff
}
Let me know if you have any questions!

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

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