It´s possible to set session timeout by user in php?
Example: 2 users are registred in my site. I want that each user can set their own session timeout.
Yes, you can set a custom session timeout for each user. You can use the method as described in How do I expire a PHP session after 30 minutes? but store the absolute expiration time instead:
// set expiration time
$_SESSION['EXPIRES'] = time() + $customSessionLifetime;
// validate session
if (isset($_SESSION['EXPIRES']) && (time() < $_SESSION['EXPIRES'])) {
// session still valid; update expiration time
$_SESSION['EXPIRES'] = time() + $customSessionLifetime;
} else {
// session invalid or expired
session_destroy();
session_unset();
}
Here $customSessionLifetime can be set differently for each user. Just make sure that its value is less than or equal to session.gc_maxlifetime and session.cookie_lifetime (if you use a cookie for the session ID).
Related
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);
There is a configuration setting in Codeigniter for setting session expiration:
$config['sess_expiration'] = 14400; //in seconds
But this applies for all types of user roles (admin/frontend users). I would like to set a lifetime session for an admin and just want to apply above setting for frontend users.
How could I achieve that?
Session data get stored at server and it get destroy if browser will get closed. For lifetime login you need to make use of cookie
Ex. "Remember me option"
If you want to implement with session you need to do it manually: Ex.
if ($ROLE != 'admin' && isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
I have given example of core php you can implement it in codeigniter with
$this->session->userdata('LAST_ACTIVITY');
$this->load->helper('cookie');
$cookie = $this->input->cookie('ci_session');
$this->input->set_cookie('ci_session', $cookie, '31557600');
Although I'm not sure its a good idea to make a session never expire, you could probably set the session cookie to expire one year in the future if the user is logged in as a admin.
What I want to do it cause an action when a cookie expires. For example i have a cookie:
setcookie('loggedIn', true, time()+ 3600);
When the cookie expires I would like to be able to redirect them to a different web page automatically and call a php script that would log the user out.
You can check it via $_COOKIE.
if(!isset($_COOKIE['loggedIn'])){
header('Location: /path/to/another/page');
exit;
}
You can code it in a separate file and include it in every page OR you can implement it in XHR.
It sounds as though what you're trying to do is automatically log users out after some amount of time. Cookie expiration is not an appropriate way to do this — the expiration date of a cookie can be changed by the user, and cookies can be deleted without reaching their expiration date. (For instance, if a user clears cookies in their browser, or uses a private browsing session.)
An appropriate way to log a user out automatically would be to store the expiration date in the session, e.g.
// during login
$_SESSION["valid_until"] = time() + 3600 * 3; // stay logged in for three hours
// then, during page startup
if ($_SESSION["valid_until"] < time()) {
session_destroy(); // or store data in the session to indicate it's inactive
header("Location: error.php?err=session-timeout");
exit();
}
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.
I'm using PHP5 here. I have made a login system that check's the username and password against the records in the database. I want to use sessions to store the logged value. For example, when I reach the zone where I "log in" the user succesfully:
if($errors = 0) {
$_SESSION['logged'] = "1";
}
The problem is that I want the $_SESSION['logged'] to stay active for let's say 5 minutes so when I do a if($_SESSION['logged'] == "1") after this time to return false. Also, I would like to delete this session after the user closes the browser. Basically, I want a session configuration so that the user can safely leave his desk and when him or somebody presses refresh after 10 minutes or enters again after the browser has been closed, the session to be already removed, and the access to be restricted.
Can anybody help? Thanks.
Use session_set_cookie_params() to change the lifetime of the session cookie. Note that by default, it is set to 0 which means that the cookie is set until the user exits the browser. You can do this in the following way:
/* Set to 0 if you want the session
cookie to be set until the user closes
the browser. Use time() + seconds
otherwise. */
session_set_cookie_params(0);
session_start();
Then check for the last activity time, updated each time someone visits a page.
if(($_SESSION['lastActivity'] + 300) < time()) {
// timeout, destroy the session.
session_destroy();
unset($_SESSION);
die('Timeout!');
} else {
$_SESSION['lastActivity'] = time();
}
Instead of setting it to one, why don't you set $_SESSION['logged_time'] = time(); and then check the time against time() in your application?
If you'd like to actually expire the entire session, the exact specifics can change depending on your session handler, but for the default session handler (and any other well behaved session handler) you'll want to check out http://us3.php.net/manual/en/session.configuration.php
You can change the configuration setting session.cookie_lifetime, e.g. in php.ini or a .htaccess file:
session.cookie_lifetime specifies the
lifetime of the cookie in seconds
which is sent to the browser. The
value 0 means "until the browser is
closed." Defaults to 0.
This means (I think) that you can't have both expiry based on a timeout and expiry when the browser is closed. So maybe the best bet is to keep the default and set your own timer in $_SESSION as others have suggested, thus rendering this answer pointless.
Sessions stay alive aslong as the user stays on your site. You will have to use cookies to set a specific timeout.