Keep User Logged In at All Times - php

By using $_SESSION['loggedin'] = true, my users will only be logged in until they close their browser.
How can I keep them logged in forever? (like Facebook or Stack Overflow)

First of all, you do need to set your session timeout to a longer length. I would be conservative and do 30 days, opposed to previously recommended time() * 9999999999999. Setting the session timeout to a long time will ensure that your session isn't deleted on browser close.
Second of all, you need to decide where to set this timeout. If you're only running one site from a specific server, just modify the php.ini file. You're looking for something called session.gc_maxlifetime.
Lastly, you must be cautious of doing this. Sites like Facebook and GitHub require you to reconfirm your password before making account-level changes. So, keep security in mind when setting long timeouts.

The default PHP session is 24 minutes.
You need to use
$_SESSION['timeout'] = time() * 9999999999999; // infinity
Make sure that you regenerate a session every now and then to protect against session stealing.

Related

how to keep alive php sessions for login on live server? [duplicate]

How can I keep the user's session active, even if they accidentally closed their browser. Like in Facebook for example.
If you log in to their site and you close the tab or the browser, when you open a browser again and visits Facebook, they will automatically detect the active user and will not redirect you to the log in page.
How do I do that?
There's two relevant settings that control session's lifetime.
The first is session.cookie-lifetime. This is the lifetime of the cookie, which by default is 0, which means the cookie is destroyed when the browser is closed. You can set a longer lifetime by increasing this variable. It is relative to the server time, so you need to account for differences in the time in your clients' machine and your server's. Assuming they were the same, setting the option to i.e. 3600 would mean the session would expire in an hour. If you want to keep the session alive for a very long time, you increase this number.
However changing this value is not enough. There's also session.gc-maxlifetime, which is the time after which the session data is seen as garbage in the storage and is destroyed. This differs from session.cookie-lifetime because this option checks the last access time of the session data, so it is relative to the time the session data was last used (i.e. when the user was last active). Even if you set your session.cookie-lifetime to a high value, it'll not be enough because session.gc_maxlifetime is relatively low usually (1440 is the default, which is only 24 minutes).
While you can set these settings both to relatively high values and have it working, I would recommend against doing so, as this will leave a lot of unnecessary session data hanging around in your session storage, due to the GC not collecting actual dead session (which also increases the chance of someone hijacking a session in a system that is not properly secured). A better approach is making a remember me cookie. Basically you assign the user's ID and some authentication token that you store in the database for each user (this is to prevent someone spoofing the cookie) in the cookie, and give it a long lifetime. In your application's initialization code you'll check if the user is logged in. If he/she is not logged in, you'll check if the remember me cookie is set. If it is, you pull the user from the database based on the user ID in the cookie, and then validate the authentication token in the db is the same one as in the cookie. If they match, you simply create the session and log the user in automatically.
For anyone that come across this same issue, to keep the session cookie set for a long time is easy, on the login form, when you are creating the session for first time use this code, it will set the cookie time for a year (use your own time as its needed).
ini_set('session.cookie_lifetime', 60 * 60 * 24 * 365);
ini_set('session.gc-maxlifetime', 60 * 60 * 24 * 365);
session_start();
That should set the PHPSESSID cookie and your session will be safe... but is not the most secure way, so use it if you don't mind security issues
By default, PHP keeps a user's session open until their browser is closed. You can override that behaviour by changing the session.cookie-lifetime INI setting:
http://www.php.net/manual/en/session.configuration.php
However please see rekot post for a full answer
You should use cookies: http://php.net/manual/en/function.setcookie.php
Just store there some unique value that will help you identify the user.
Anyway, I strongly recommend you using some kind of framework, like CodeIgniter or Zend Framework, unless you're just learning how it works. It is easy to make critical mistakes in such a code and most frameworks are already well tested and safe to use.

Can't extend session expiry

I am currently building a website where basket data etc is being stored in session variables. The issue is that with default settings the session expires at the end of the session.
I have tried a range of suggestions as to how to modify the session expiry date, and on using $params = session_get_cookie_params(); var_dump($params); I can see that the session expiration has changed to what I set.
My issue using the web inspector on Safari 8.0.8, the session cookie still says to expire at the end of the session. I have also tried manually updating the cookie using the setcookie() command.
Currently I'm running on a localhost, but with a view to initially deploy on a shared web server.
Is this expected? A problem with safari? Any ideas?
Session timeout is a notion that has to be implemented in code if you want strict guarantees; that's the only way you can be absolutely certain that no session ever will survive after X minutes of inactivity.
If relaxing this requirement a little is acceptable and you are fine with placing a lower bound instead of a strict limit to the duration, you can do so easily and without writing custom logic.
Convenience in relaxed environments: how and why
If your sessions are implemented with cookies (which they probably are), and if the clients are not malicious, you can set an upper bound on the session duration by tweaking certain parameters. If you are using PHP's default session handling with cookies, setting session.gc_maxlifetime along with session_set_cookie_params should work for you like 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!
This works by configuring the server to keep session data around for at least one hour of inactivity and instructing your clients that they should "forget" their session id after the same time span. Both of these steps are required to achieve the expected result.
If you don't tell the clients to forget their session id after an hour (or if the clients are malicious and choose to ignore your instructions) they will keep using the same session id and its effective duration will be non-deterministic. That is because sessions whose lifetime has expired on the server side are not garbage-collected immediately but only whenever the session GC kicks in.
GC is a potentially expensive process, so typically the probability is rather small or even zero (a website getting huge numbers of hits will probably forgo probabilistic GC entirely and schedule it to happen in the background every X minutes). In both cases (assuming non-cooperating clients) the lower bound for effective session lifetimes will be session.gc_maxlifetime, but the upper bound will be unpredictable.
If you don't set session.gc_maxlifetime to the same time span then the server might discard idle session data earlier than that; in this case, a client that still remembers their session id will present it but the server will find no data associated with that session, effectively behaving as if the session had just started.
Certainty in critical environments
You can make things completely controllable by using custom logic to also place an upper bound on session inactivity; together with the lower bound from above this results in a strict setting.
Do this by saving the upper bound together with the rest of the session data:
session_start(); // ready to go!
$now = time();
if (isset($_SESSION['discard_after']) && $now > $_SESSION['discard_after']) {
// this session has worn out its welcome; kill it and start a brand new one
session_unset();
session_destroy();
session_start();
}
// either new or old, it should live at most for another hour
$_SESSION['discard_after'] = $now + 3600;
Session id persistence
So far we have not been concerned at all with the exact values of each session id, only with the requirement that the data should exist as long as we need them to. Be aware that in the (unlikely) case that session ids matter to you, care must be taken to regenerate them with session_regenerate_id when required.

How to keep a PHP session active even if the browser is closed?

How can I keep the user's session active, even if they accidentally closed their browser. Like in Facebook for example.
If you log in to their site and you close the tab or the browser, when you open a browser again and visits Facebook, they will automatically detect the active user and will not redirect you to the log in page.
How do I do that?
There's two relevant settings that control session's lifetime.
The first is session.cookie-lifetime. This is the lifetime of the cookie, which by default is 0, which means the cookie is destroyed when the browser is closed. You can set a longer lifetime by increasing this variable. It is relative to the server time, so you need to account for differences in the time in your clients' machine and your server's. Assuming they were the same, setting the option to i.e. 3600 would mean the session would expire in an hour. If you want to keep the session alive for a very long time, you increase this number.
However changing this value is not enough. There's also session.gc-maxlifetime, which is the time after which the session data is seen as garbage in the storage and is destroyed. This differs from session.cookie-lifetime because this option checks the last access time of the session data, so it is relative to the time the session data was last used (i.e. when the user was last active). Even if you set your session.cookie-lifetime to a high value, it'll not be enough because session.gc_maxlifetime is relatively low usually (1440 is the default, which is only 24 minutes).
While you can set these settings both to relatively high values and have it working, I would recommend against doing so, as this will leave a lot of unnecessary session data hanging around in your session storage, due to the GC not collecting actual dead session (which also increases the chance of someone hijacking a session in a system that is not properly secured). A better approach is making a remember me cookie. Basically you assign the user's ID and some authentication token that you store in the database for each user (this is to prevent someone spoofing the cookie) in the cookie, and give it a long lifetime. In your application's initialization code you'll check if the user is logged in. If he/she is not logged in, you'll check if the remember me cookie is set. If it is, you pull the user from the database based on the user ID in the cookie, and then validate the authentication token in the db is the same one as in the cookie. If they match, you simply create the session and log the user in automatically.
For anyone that come across this same issue, to keep the session cookie set for a long time is easy, on the login form, when you are creating the session for first time use this code, it will set the cookie time for a year (use your own time as its needed).
ini_set('session.cookie_lifetime', 60 * 60 * 24 * 365);
ini_set('session.gc-maxlifetime', 60 * 60 * 24 * 365);
session_start();
That should set the PHPSESSID cookie and your session will be safe... but is not the most secure way, so use it if you don't mind security issues
By default, PHP keeps a user's session open until their browser is closed. You can override that behaviour by changing the session.cookie-lifetime INI setting:
http://www.php.net/manual/en/session.configuration.php
However please see rekot post for a full answer
You should use cookies: http://php.net/manual/en/function.setcookie.php
Just store there some unique value that will help you identify the user.
Anyway, I strongly recommend you using some kind of framework, like CodeIgniter or Zend Framework, unless you're just learning how it works. It is easy to make critical mistakes in such a code and most frameworks are already well tested and safe to use.

How to delete session cookie on browser close

How to delete session cookie on browser close, or optionally detect and force "new" session for a returning user. I want to prevent storing session cookies by "session managers" like addons in firefox and such.
I guess you could use this :
session_set_cookie_params(0);
session_start();
Destroy PHP Session on closing
Session manager are designed to save session cookie : I don't think you can prevent their behavior.
However, you can set your php configuration to have a non-used session garbage collected really fast : Then the session, after a few amount of time (basically, 1 hour), will be invalidate. See the session.gc_maxlifetime parameter.
fortunately a website can't force anything to happen on the clients machine. if you don't want to rely on the browsers cookie-management and those addons, one way would be to not use cookies for sessions and use the good old session-id get parameter instread (or, alternatively, set the session-lifetime to something like 1 or 2 hours, but this isn't exactly what you wanted)
I don't think you'll be successful on this route.
If you need to log out the user so quickly, consider using a very short session lifetime (like, one minute) and keeping the session alive using a JavaScript setInterval or an iframe that refreshes itself every thirty seconds.

How could I make PHP sessions / cookies indefinite

I am using a login system that sets the session variables / cookies below. Chrome, which awesomely lets you look at your cookies without too much trouble, apparently labels this as a PHPSESSID that expire "When I close my browser." Sure enough, when I log in, shut down the browser, and then open up a new browser session, I am no longer logged in.
How could I make it so the user stays logged in whether or not the browser is closed? I would like to make it so the user stays logged in (permanently, if possible) unless a deliberate logout is done.
$_SESSION['loginid'] = $row['loginid'];
$_SESSION['username'] = $u;
Take a look at session_set_cookie_params()...
The first parameter is $lifetime. Set that to a non-0 number, and that's how long they will stay logged in for in seconds. If it's 0, it'll be deleted once the browser closes. Note that you'll need to either store the session data yourself, or set ini_set("session.gc_maxlifetime", $Lifetime); as well (to prevent the server from deleting old sessions). But beware that this could eat up a LOT of disk space (And open Denial Of Service attacks where attackers eat up all your disk space by just spawning new sessions continuously)...
1 year ~= 3156000 (seconds)
I'd honestly suggest implementing a "remember me" function rather than trying to persist the session indefinitely... The remember me would use a cookie as well, but it wouldn't tie up server space for non-active users...
You just need to set an expiration date in the future on the session cookie.
You can use session_set_cookie_params to set the PHPSESSID cookie related settings.
//set cookie for 60 seconds:
session_set_cookie_params(60);
So you would just replace the value 60 with some arbitrarily high second value.

Categories