Can I make a session alive after when user closes his browser? - php

I'm trying to implement a system to keep an user logged in for a while. I can do that by using cookies and storing it into database and then identifying him.
But recently I heard a session can be alive even when user closes his browser and opens a new window. I mean can a session still be available after closing/opening the browser again (or even multiple time)?
How much time (maximum) can I use $_SESSION["LoginValidation"] in following script?
<?php
session_start();
$_SESSION["LoginValidation"] = ture;
Currently that session will be available until closing the browser.

In order to make the session persist after closing the browser you need to set an expiry time for the session cookie. A cookie without an expiry time is deleted when the browser is closed, and is normally referred to as a session cookie (which is not the same thing as a PHP session - just related).
(side note: if your browser is configured to "save open tabs" at exit, then the session cookies may be saved by the browser even though they should be deleted)
So you could just set session.cookie_lifetime to a large value. But that doesn't stop the session data stored on your server from being deleted - to keep the data for longer you need to up the value for session.gc_maxlifetime.
BUT THIS IS THE WRONG WAY TO FIX THE PROBLEM
There are security and capacity implications to implementing such persistent sessions - you should certainly NEVER implement this as default behaviour - only where the user has explicitly given their consent.
Using a "Remember me" cookie as a sort of lightweight session system is the best practice solution. Give it a random value (suggest you use a reasonably reliable source of random numbers, e.g. base64_encode(openssl_random_pseudo_bytes(64)) and a name which does not conflict with other cookies, and store it along with the data you really want to persist across the actual sessions (e.g. authenticaticated username).

Approach 1) 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.
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.
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
Or
another approach is for session to make alive even after closing of browser save session in db and get its id , and set that id in user cookie via
setcookie("name","value",time()+$int);
so you can fetch that value from $_COOKIE["name"]; use it to get session variables from data base

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.

php session and cookies

I want to have sessions persist the browser closing
So I used
session_set_cookie_params(86400 * 60, '/', 'my.domain.com', true, true);
to send a persistent cookie to the client (also with the secure flag as this is a SSL site)
which is valid for 2 months.
However, I see that after x minutes of inactivity the session variables are cleared on the server.
How can I avoid that? Essentially, I want the session variables to be stored until the cookie
becomes invalid
Thanks
Set the session.gc_maxlifetime configuration property.
The documentation is rather sparse when it comes to acceptable values for it, but I wouldn't want to go as high as two months.
You'd usually be better off storing the important data in a database, and adding it to a session when one is created with a remember me cookie.
Leave sessions for actual sessions.
With sessions you are looking at two things. The time until garbage collection cleans up the session on the server, and the time until the cookie expires.
You only changed the cookie expiration, the session will still get cleaned up. However extending the session is not a great way to solve this. Your code could change and you may end up with users having a broken session. You may need to use some sort of shared session storage like memcached that will delete the storage after a certain max time anyway.
So the way to solve this is to generate a unique one time cookie that can be used as an alternative login key. This key will allow a user to login similar to a username/password. Once its used, a new one gets regenerated.
Session variables will persist as commented below, but unless you change their default behavior, they expire when the session ends (i.e. when the browser is closed).
For what you're trying to accomplish, you should store your values in $_COOKIE variables, not $_SESSION variables.
See this article: http://buildinternet.com/2010/07/when-to-use-_session-vs-_cookie/

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.

Using a prolonged session?

I'm setting up a script that my local pub will use to show users slide shows of images, menus, etc. My URL will accept a key(uuid), from which my script will query the database for the content associated with the key based on a company_id. The site will then just rotate through images via javascript or jquery.
Before serving out the content, I would like to make sure that the session or user is authenticated meaning that there is a valid company_id associated.
I've always used $_SESSION variables for web sessions. Since there will be no real need to time out a session, would there be any flags I can set in php.ini to never time out? Or would it be more beneficial to use cookies for this type of work?
Thanks.
You are probably better off using a cookie to store a login token for the user with a distant expiry date, so they are auto-logged in. Preserving $_SESSION indefinitely would cause session files to pile up on your server wasting resources on the filesystem. Instead, a cookie can hold some token (non-guessable value) that is associated with the user in your database. Basic information can be retrieved from the database then when the user returns.
When you call session_start() the script will try and set a cookie in the users browser containing the session id, there is no need to manually set one holding a "non-guessable value" since that is what the session id is supposed to be anyway.
You can change session.cookie-lifetime in the ini file (maybe even with ini_set()) to prevent the cookie timing out at the end of the session.
Preserving $_SESSION will not cause session files to pile up indefinitely. By keeping the session alive the same file will be re-used over and over again (since it is named after the session id), and PHPs built in session garbage collector will clear up dead sessions anyway.
While in general it is a bad idea to make sessions last forever, since it's your local pub, I doubt anyone is going to try and hijack their session. (and even if they did, all they'd get is what's for sunday lunch, right?) :)
Edit:
You could also periodically regenerate the session id, to add a bit more security.

How does PHP know when to delete a session?

I thought that sessions were stored on the client side because of the session getting deleted when the browser closes. However, today I've been told that this is not true and that the session is stored on the server.
So how does a session know when a browser was closed, so that the session gets deleted?
It doesn't. There are two factors at play:
the lifetime of the cookie on the client-side;
This cookie contains the session ID. It does not have anything to do with the session data itself.
The manual probably doesn't stress this enough:
This has nothing to do with lifetime of a session
Whatever you set this setting to, it won't change how long sessions
live on your server.
This only changes HTTP cache expiration time (Expires: and
Cache-Control: max-age headers), which advise browser for how long it
can keep pages cached in user's cache without having to reload them
from the server.
the lifetime of the session data on the server-side;
The session is "activated" via a lookup with the session ID from the client. Its lifetime is controlled via session garbage collection settings discussed here.
A commenter posted on the session.cache_expire documentation page, presumably actually talking about the session data:
What most people also don't know, is that most Linux distributions
(Debian and Ubuntu for me atleast) have a cronbjob that cleans up your
session dir using the value set in the global /etc/php5/php.ini (which
defaults to 24mins). So even if you set a value larger in your
scripts, the cronbjob will still cleanup sessions using the global
value.
If you run into that situation, you can set the global value higher in
/etc/php5/php.ini, disable the cronjob or even better, do your own
session cleanup in a non-systemwide directory or a database.
As you can see, confusing abounds amongst the community when making the distinction between session tracking and session data storage.
Session is identified by a cookie, which does get stored in the browser. It can have an expiry date/time, or it can be set to expire when the browser is closed. When the cookie expires, you can't identify your session storage any more, and the session is effectively expired. It does not get deleted unless the system admins or programmers specifically make a cleanup.
EDIT Just noticed the PHP tag. For how PHP cleans up its session files, check this question.
The server has no way of knowing when the browser is closed.
Closing the browser will delete the session ID cookie from the client.
The session is deleted from the server once there are no requests in a given amount of time (the session timeout).

Categories