Can we create endless session in php? - php

Normally a php session expires when the user closes the browser. Is is possible to create a session in php that never expires, doesn't matter how many times user closes and restart the browser?
Thanks

Not strictly endless, but you can set the cookie lifetime to two years or so which comes pretty close:
session.cookie-lifetime ini setting
session_set_cookie_params()Docs function to set them programmatically.
The session cookie won't be deleted then if the user closes the browser.
Take care that your session data store keeps the data as well that long. This is important. And keep in mind that you need to store all user's data for this large time-span, so you should have enough space available.
This does not work at all if the user disables cookies in her or his browser.

It is never endless. But you can set cookies/session for more than 10 years in future. However, your server is gathering more and more session files, be aware of that. I collected almost a million files in my tmp directory

No, the best you can do is set a cookie with an expiration date far in the future.
Even then, the user can just delete it without even closing the browser or leaving the site, so don't rely on it.

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 expires immediately when client's clock is set in the future

I have developed this PHP web application which is now running for some months. Suddenly one of the users complained that he was able to login, but the session was terminated as soon as he clicked on any button! The same problem happened on different browsers.
After some tests I realized that a brand new session ID was created every time the user clicked on any button, probably because the original session was expired.
For whatever reason I took a glance at the user's computer clock and... surprise! His clock was 3 months in the future! I didn't know if such thing could have any relation to the failure, but I did fix the clock. Still it didn't work. I erased all cookies. Still nothing. So I restarted the browser - and then it started working again!
The closest information I got about this issue was Shimon Amit's answer to this question. Good, now I know that the clock "misconfiguration" is the cause. The problem is... I cannot keep every customer's computer clock under control. Some of them may have their computer clocks set in the future.
My question: is there any solution for this? Any trick? I don't want customers to face such errors as they may find it "lame" and break their trust on the application, even though it's not really my fault (in a sense).
Session cookies (like all cookies) are controlled and deleted when expired by the client browser. Even if you set a far out expire date (which you might not want to do anyhow) all the client needs to do is move his clock even farther forward and it will expire.
You can extend your session timeout to a later date. Perhaps you can use cookies that don't expire (sessions are related to cookies on the client side) Otherwise, your client's browser is just doing what it's designed to do.
EDIT: Javascript Option
This is a total hack, but you COULD use javascript to get the current time on the client machine and send it back to the server, then adjust the timeout on your session cookie to expire three months after that. See http://www.w3schools.com/jsref/jsref_gettime.asp
Once you have retrieved the client time, you can reset the session expiration using session_cache_expire(). http://www.php.net/manual/en/function.session-cache-expire.php
EDIT: 100% Server Side Option
Another option that I thought of would be to set a session cookie with no expiration, but track the time the cookie was set on the server, say in a MySQL table. You would also need to keep track of the last activity. Whenever a logged in user makes a request, you could check the start time of their session and their last activity. If the current time is greater than your acceptable timeout for either of these, then destroy the session server side and bring them back to the log in page. If the session is still ok, then update the last activity associated with that user so you can compare on the next request. No client side code necessary.
I fully agree with #MarcB's comment that you can't assume responsibility for how grossly misconfigured a user's machine could be. If you really want to make a difference in this regard I would suggest using PHP to output a small snippet of javascript that includes the time on the server. The snippet would compare that time to the time on the client computer and raise an alert if the time differs by more than X from the server. [say, 24hours or so]
Any trick?
Use session cookies. Not session in the meaning of PHP sessions, but browser session. Session cookies are stored until the user closes the browser. They are immune to whichever clock the user has set her computer. They will last until the browser is closed.
That is normally appropriate for PHP-session related cookies.
For PHP you need to ensure that the session cookie parameter lifetime is configured to 0 before the session starts. That is either the ini setting session.cookie_lifetime or by calling the session_set_cookie_params function.
For a more detailed description of cookie parameters, see the documentation of the setcookie function.
Second part of the trick is that you place a session start timestamp and a last activity timestamp into the PHP $_SESSION. Those are server based so have always the same base.
Check them, e.g. if the session is too old, last activity too long ago etc., destroy the session and force the user to login again.
You could even use that second part of the trick to combine it with a cookie that has it's expiry 10 years in the future (okay, browser might not like that, maybe you just want your three months).
Try to disable the session timeout or at least set it far into the future. That should do the trick.

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.

storing sessions temporarily

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

Categories