Set session timeout based on the user role in Codeigniter - php

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.

Related

Performing an action on cookie expiration

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

Codeigniter - Session expiration and "remember me" feature

I'm building a "Remember Me" feature in Codeigniter, normally I see libraries/projects setting a cookie on the user with a token, this token gets saved in the database and is compared each time the user accesses the website.
In Codeigniter we can set the session expiration time though, this lead me to try a different approach, this is what I did:
I set the session_expiration in config to 0 (infinite session)
If the user leaves "Remember me" unchecked, I set a 2 hour time in the session and session destroy on window close.
So my login code looks like this:
if (!$this->input->post('remember_me')) {
$this->session->sess_expiration = 7200;
$this->session->sess_expire_on_close = TRUE;
}
$this->session->set_userdata($session_data);
And my config file:
$config['sess_expiration'] = 0;
$config['sess_expire_on_close'] = FALSE;
I don't see people using this solution on projects, I have tested this out and it seems to work fine though.
SO, for my question, would you say this a safe practice to do? Any security dangers I should know about? Any input on this solution vs cookie+database token would be great.
The simpliest solution that I have found for this problem is to just modify the cookie created by Codeigniter by this way:
$this->session->set_userdata('user', $user); // a cookie has been created
if($this->input->post('remember_me'))
{
$this->load->helper('cookie');
$cookie = $this->input->cookie('ci_session'); // we get the cookie
$this->input->set_cookie('ci_session', $cookie, '35580000'); // and add one year to it's expiration
}
Also this can be done by editing/extending system Session library.
First: Set regular session expire time in config file.
Second: In user login function add remember me check-
if($remember)
{
$data['new_expiration'] = 60*60*24*30;//30 days
$this->session->sess_expiration = $data['new_expiration'];
}
$this->session->set_userdata($data);
Third: Edit system Session library [I am not sure whether extending Session will work or not]
Go to this line in sess_read() method
if (($session['last_activity'] + $this->sess_expiration) < $this->now)
Before that line add following code
if(isset($session['new_expiration'])){
$this->sess_expiration = $session['new_expiration'];
}
This works fine for me.
I can't say it's not right, but I can tell you my way of doing this:
First I set the session to expires on browser close with a default uptime of 7200.
Then:
The login sets session userdata
The "remember me" sets a separated cookie (I store an encrypted hash containing user's email+password+id ie: md5(pass+email+id))
Every time the user loads a page I control if the remember me cookie exist, if exist I create the user session.
The only thing I know is that session, uses an encryption key, a malicious attacker will take time to decrypt, so the less a session key exist the less time attacker has for decrypt the current key.
I always avoid session to not expire, so the Remember me, is always something not good for security I think, but anyway is the user to choose or not if to use that feature ;)

php session unset

Is it possible to unset a specific user session (one who is banned from the site)?
Each session contains the user's username.
Or is the only way to writing sessions in the database and checks whether the user is deleted from that record?
Thanks for any suggestion.
PHP doesn't keep track of what session IDs have been issued - when a session cookie comes in on a request and session_start() is called, it'll look in the session save directory for a file named with that session's ID (sess_XXXX) and load it up.
Unless your login system records the user's current session ID, you'll have to scan that save directory for the file that contains the user's session, and delete the file. Fortunately, it could be done with something as simple as:
$session_dir = session_save_path();
$out = exec("rm -f `grep -l $username $session_dir/*`");
You'd probably want something a bit more secure/safe, but that's the basics of it.
Just remove the user from your database.
I assume that you are checking login credentials.
You can add a timeout to your sessions like so:
define('SESSION_EXPIRE', 3600 * 5); //5 hours
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > SESSION_EXPIRE) {
session_regenerate_id(true); // change session ID for the current session an invalidate old session ID
session_destroy();
session_start();
$_SESSION['CREATED'] = time(); // update creation time
}
I think the best method would be before allowing the user to comment, have PHP read your database and check if the individual has publish permissions. If not return an error.
Another thing you could do, which Facebook does, is have an AJAX call checking a PHP file every few minutes. The PHP file simply returns whether the user is logged on or off and if they are logged off, Javascript redirects them off the page.

set php session timeout by user

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

PHP session lifetime problem

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.

Categories