storing sessions temporarily - php

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

Related

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

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

Is it possible to prevent php session from destroying when you close browser?

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.

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/

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.

PHP $_SESSION Implementation

Does anyone know how PHP maps session IDs to $_SESSION arrays? In other words, given session ID x, where does PHP pull the values from to populate the $_SESSION array?
And given a session ID and the url it came from, is there any possibility of someone being able to gain access to the values in the $_SESSION array?
By default, PHP uses the files session handler. These files are stored based on the session.save_path setting, but defaults to the system's temp directory (a highly insecure location, consider changing it)
This session handler stores each session as a serialized PHP array in a file named with the session ID.
If you can find out a session ID prior to it being cleaned up by the session garbage collection routine, it can be hijacked, as PHP does not internally do any sanity checks. You may wish to do your own by storing the user's IP address in the session and comparing it to their current IP, clearing the session if they don't match.
session.gc_maxlifetime controls how many seconds a session will be considered valid. After this point, the session has a small chance of being deleted every time a request occurs. Default is 1440 seconds (or 24 minutes).
By default, this chance is 1%, but can be altered by adjusting the session.gc_probability and session.gc_divisor values (they default to 1 and 100 respectively).
There are other session handlers as well, such as the ones included with the memcache or memcached extensions. There was once one based on the libmm shared memory library, but I believe that has been discontinued.
Session info is stored on server filesystem. There's configuration parameter session.save_path in php.ini. Some info about sessions security is given here: http://www.php.net/manual/en/session.security.php
Session data is usually stored in temporary files on disk (see the session.save_path setting) and the filename reflects the session ID.
In general, yes, if someone gets hold of another user's session ID and sends it along with his own request, he will gain access to that user's session. One way of solving this is to bind sessions to IP addresses and invalidate the session when a request arrives from a different address.
No, there is no possibility!
...unless your code or the code of any component used is insecure.
With the default implementation of sessions (which can be replaced by a custom one if needed) the data is stored in local files. Your server receives the session ID from the client in a cookie, finds the corresponding local file on your server and populates data into $_SESSION.
Gaining access to this data requires file-level access on the server, which is not impossible, unless your server is secure enough.
You can also write your own session handler to save the session to a database.
Also, if you want to make it harder to pin down the session ID, regenerate the session ID at strategic times (on privilege elevation, etc) -- or as often as you want.
Pass session_regenerate_id() the argument True to destroy the old session data.

Categories