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/
Related
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
We want to use sessions instead of cookies for keeping track of a few things. However, when I close my browser, and I reopen a page to echo a session var, it doesn't exist (which is how it is suppose to be). Is it possible to prevent this from happening with some magic or anything?
This is not a duplicate question, all I see are people wanting to destroy sessions, I want to do the opposite and retain the session for as long as possible.
Any knowledge would be appreciated.
The right way of doing this is with a database, you can mimic or control php sessions and store them in a database instead of in a file ( as normal ). Then once you have control of the data you can base renewing session via the ip address or better yet by login.
So say a user logs in and then you need to store some data, you store that in the session but php will store it in your database table ( when configured correctly ). Latter the user comes back, initially any visitor would get a fresh session, however once they login you would be able to retrieve the past session they had. You generally don't have much control on if or when a client will delete expired cookies.
This topic is too extensive to put just a few pieces of example code but I did find this small article on the topic.
http://culttt.com/2013/02/04/how-to-save-php-sessions-to-a-database/
The guts of it is to use this function, session_set_save_handler
http://php.net/manual/en/function.session-set-save-handler.php
Once you have control of the data you can do whatever you want, however I would caution you about relying only on the IP address and it would be preferable to use a login system for something like this to prevent serving the session up to the wrong visitor.
You cannot reliably control what happens on the client side, even using a separate cookie would not be reliable and would have the disadvantage of storing data on the client where it could be accessed instead of keeping it on your server. Sessions are controlled by cookies but the data in them remains on your server, the cookie just identifies the client.
As a side note, I personally dislike using sessions at all. It may be possible to store what you need in the url, then it can be bookmarked. The classic example would be input for a search form ( via $_GET ) or for paging purposes. There is nothing wrong with doing this if it's not secure data. The problem with sessions is if the data is for a page such as my "classic example" or for paging you get only one session, so you would only be able to have one set of search data at a time, in the url you could have several sets of search data open at once. That said it does largely depend on what you need to save or persist.
Reset the session cookie manually.
$lifetime=60*60; // duration in seconds
session_start();
setcookie(session_name(),session_id(),time()+$lifetime);
You can use session.gc_maxlifetime and session_set_cookie_params, i.e.:
// server should keep session data for AT LEAST 1 Year
ini_set('session.gc_maxlifetime', 3600 * 24 * 365);
// each client should remember their session id for EXACTLY 1 Year
session_set_cookie_params(3600 * 24 * 365);
session_start();
Note:
You can also change the session options globally by editing php.ini -
Session configuration options
PHP sessions use session cookies. Browsers have their own ways of dealing with them but they all consider them to be trash if you close the browser.
Session cookies are not and can not be made persistent. If you need persistent cookies, just use a regular cookie to save a user identification code that your server would recognize, and save their session information in a database or flat file indexed on that id code.
Note that accumulating sessions on the server progressively causes important performance and security concerns.
Note on other answers: All of them mention ways to extend the session cookie expiration which will not overcome the regular behavior when you close your browser window.
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.
I made a fiddle with my code and I am using sessions to memorize the URL and local storage to store the values I am putting in. The problem here is that after 2 days of not touching the file I found the session values were "emptied" so I am guessing destroyed. I am not sure if the same happened to the localstorage. I know sessions are cookies not made to last long so I will need to figure out cookies and use those any ideas on that would help. Anyone know if localstorage has a time limit as well?
http://jsfiddle.net/y8Uju/16/
Your session wasn't "emptied". It most likely expired, as per the session.gc_maxlifetime, and cleaned up by the session garbage collector.
If you want to use long-duration persistent sessions, you'll have to disable the session cleanup functionality, or set a longer expiry time.
I know that sessions are server side, so, it is possible to save a session even if the browser is closed?
For example save a session for one day.
Please do not suggest "cookies", in this case must be implemented sessions.
thanks
They are saved already (see your php.ini file for the session path)... In fact, the real issue lies in garbage collecting them.
If you want to store them longer, edit your php.ini file or, define a custom session handler:
http://www.php.net/manual/en/function.session-set-save-handler.php
session_set_cookie_params I think is what you are looking for. If you are storing the session in a cookie, this will allow you to set the lifetime of that cookie. So the user can come back anytime within that time frame and still have their original session.
Side Note
Give this a read for more about session lifetimes etc.
How do I expire a PHP session after 30 minutes?
php_value session.gc_maxlifetime 86400
You can set the above in .htaccess or modify session.gc_maxlifetime in php.ini
This defines how long PHP will have a session file for the user on the server before garbage collection (the example above will allow the server to maintain the sessions for 1 day), however sessions generally do rely on a session id cookie so if the browser is reset or clears the cookie the user won't re-attach to their web session (you are actually setting a session ID cookie to use sessions in most cases even if you don't realise it.)
You can create a database and store there the sessions and on client side just store $_SESSION['id'] wich is the id of the session in the database. But this will become a headache when you will have to store more and more variables in the session.
Like Gumbo said, pass it in the URL. But how I like to solve this is, instead of passing the SESSION_ID through the Url, just make it a hash, or encoded data.
Then whenever this user comes to your page. you can check in your headers if this hash/encoded-data is still in the valid time frame, and if this 'anonymous' user has permissions for thay zone.
THE DOWNSIDE: If this user passes around this link, anyone could access the data
THE UPSIDE: Extremely portable, and easy to implement
Store the SESSION_ID in a database bound to the users IP. whenever this user logs back in, start the session via setting the SESSION_ID with session_id
THE DOWNSIDE: A lot more work, and if the users ISP changes their generated IP regularly this won't work
THE UPSIDE: Even if he erases the SESSION_ID cookie you will be able to continue the session
there are many ways to do this but beign an artisan you could:
make an script that save each session for your users inside a file
OR
go to PHP.ini and change the session life time
OR
use the session_set_save_handler function more info here