What I want is to be able to save a session variable for 12 hours so user don't need to re-log in.
I'm using something like this:
if(ini_get('session.gc_maxlifetime') !== 3600*12) {
ini_set('session.gc_maxlifetime', 3600*12);
}
if(ini_get('session.cookie_lifetime') !== 3600*12) {
ini_set('session.cookie_lifetime', 3600*12);
}
session_start();
And I've echoed the vars and they all are set properly. But as long as browser gets closed session gets destroyed and user must log in.
I've read recently (but can't find the resource now) that one should change the location folder for long running session cookies because of garbage collection.
Where/How do I configure that?
Thanks!
This code looks ok.
You should check PHPSESSID cookie on the client side first to ensure that it is really set to expire in +12 hours. Since you are saying that "as long as browser gets closed session gets destroyed and user must log in" the cookie is not set to expire in +12 hours. Are you starting the session after you set session.* variables?
Related
Could anyone tell how to maintain a session (in PHP) so that the session contains are preserved and are accessible even after the browser is restarted.
In general a session expires with the closing of a browser, but I want the session NOT TO BE CLOSED so that the session data's can be accessed the next time the browser is used.
Use session_set_cookie_parameters() to give the session cookie a non-zero lifetime before starting the session, or set session.cookie_lifetime to non-zero.
It's oxymoron.
Session stands for "until browser is closed".
Session is something that expires.
If you don't want it to be expired, you're probably don't want a session at all.
You are probably messing session with cookie or database.
Session in php (and in most web technologies) work like this :
You store a session id in a cookie on the client computer.
When the client come to your site he send you the session id.
The server find the session datas in a file with the session id and load it.
So closing the browser has not effect on the session, but if the browser empty the cookie when you close it (I don't think any browser do such a thing).
If you wana be sure the user is always logged in, you can store it's user/password in his cookies but it's not really safe.
The easiest and best i have found is that instead of just session_start we should input this on each page there is a session
$expire = 365*24*3600; // We choose a one year duration
ini_set('session.gc_maxlifetime', $expire);
session_start(); //We start the session
setcookie(session_name(),session_id(),time()+$expire);
//Set a session cookies to the one year duration
You can do something like this: (see session_set_cookie_parameters() and session_name())
// long long time
$sessionTime = 365 * 24 * 60 * 60;
$sessionName = "my_session";
session_set_cookie_params($sessionTime);
session_name($sessionName);
session_start();
if (isset($_COOKIE[$sessionName])) {
setcookie($sessionName, $_COOKIE[$sessionName], time() + $sessionTime, "/");
}
For $sessionTime, also refer to this question
This can be done if you use cookies instead of sessions.
I've seen various questions like mine, though none provide the correct answer.
I've a PHP script:
session_start();
setcookie(session_name('DSWLogin'),session_id(),time()+2*7*24*60*60, '/');
//This will only be set once (when the user logs in)
$_SESSION['test'] = 'Yup, I am working';
if (isset($_SESSION['test'])){
echo 'Session is set and ready!';
} else {
echo 'No session was set...';
}
and that all works fine except after a browser restart, my PHP script ignores the session.
When my browser hasn't restarted yet, it'll echo 'Session is set and ready!'; just fine.
And when I look into my cookie tab, it indeed says a cookie, named DSWLogin has been set with a certain value.
When I restart my browser, my cookie tab still says that a cookie, named DSWLogin has been set with the same value it had before the restart, so it is still there!
But my PHP script apparently ignores is, and outputs 'No session was set...'...
Thanks in advance,
Isaiah v. Hunen
What you are trying to do is not really the correct way to achieve this. Sessions have two parts, a cookie with a session id set by default to expire at the end of the session (usually browser close) and a server side storage mechanism that is cleaned up automatically after a certain period of time after the last request was received.
What you are trying to do is extend the session to two weeks. While you could change the cookie settings and increase the timeout to session garbage collection doing this is not very reliable.
Instead you want to look at using a one time key stored in a cookie which acts as an alternate login path. This cookie can recreate the session just like a normal login would. There are some details that need to be considered for this to remain secure, but it will do what you are attempting to achieve.
Just because you are setting your session_id in some cookie doesn't mean it is THE session cookie. Most browsers will purge session cookies on browser close. This is what you are seeing. Look at the cookies in your browser that are set when your session is valid and compare this to the cookies that are still remaining after browser restart. You will notice your true session cookie has gone missing.
Quoting the manual:
The session name is reset to the default value stored in session.name
at request startup time. Thus, you need to call session_name() for
every request (and before session_start() or session_register() are
called).
Also if you want to change lifetime of session cookie, use session_set_cookie_params instead of forcing your own cookie.
Also read about session garbage collection and configuration, changing cookie lifetime might not be enough.
This may seem trivial.
What will happen to a session that was never destroyed/unset/write_close-d?
Lets just say I have set the session to never time out. What will happen to the session if person finds himself at the login page and logs in using different credentials. Also just for the testing purpose, the login page doesn't have redirect if session is set.
Will it overwritten and destroyed or never destroyed?
If your login sets all of the session variables, the session will be effectively destroyed by the new values.
If there is a variable that's in the session that isn't overwritten by the login, then it will persist. The session is overwritten rather than destroyed and set again.
if he logs in using different credentials with an already started session, the session will be simply overriden...
in the case, that the user deletes his cookies etc., a new session will be generated and the old one MAYBE will retain as session-file or in DB...
(depends on the php-settings)
Sessions will be destroyed implicitly after timeout. The number of seconds for timeout can be specified in php.ini . Default is 1440 seconds or 24 minutes.
You have to set some arbitrarily large value for session.gc-maxlifetime to seemingly never time out.
If you let someone else to go through the login process, it must overwrite the existing session. But all this ultimately depends on your code.
I have stored the user id when the user login , however, i found it sometime will lost , what is the common reason of session lost?
I have used the timeout plugin (idle for sometime will warning and help you logout)
and there are some javascript to transfer between pages
You have edited the list. <a href='view.php' onClick='window.location.reload()'>Back</a></div>
<input type="button" value="Back" onclick="location.href='add.php'" class="btn" style="width:100px"/>
and unset the session, but it should not be the reason?
$(function(){
$("#closeTab").click(function() {
$.post("clear.php",function(data){
window.parent.$('#tt').tabs('close','Create List');
location.reload();
});
});
});
clear.php
if (isset($_SESSION['lname']))
unset($_SESSION['lname']);
if (isset($_SESSION['creminder']))
unset($_SESSION['creminder']);
if (isset($_SESSION['subscribe']))
unset($_SESSION['subscribe']);
if (isset($_SESSION['unsubscribe']))
unset($_SESSION['unsubscribe']);
This is used for store session
$user=$_SESSION['username'];
Thank you
PHP manages sessions this way:
When session_start() a file on the webserver is created. The file is a text file called for example session1234. On the user browser a cookie is set the cookie contains the value "session1234". Every time the user calls a page on the same domain the browser silently sends that cookie.
So the user is recognized and user's session data are taken out from the session file on the server.
Reason a session expire:
Usually when logout from webapplication we use session_destroy() which destroys the file on the server session1234. So if user calls again the site with cookie content session1234: no file session1234 exists on the server (has been removed with logout) the user is not authenticated
Timeout occurs: file session1234 is removed from server default 20 min (configurable in php.ini). If user calls again the site, same as before. Every time the user take an action (call the server) the server updates the time to live of the session file
Users clear browser cookie (can happen if someone want to clear the history of the browser): cookie is lost, the browser doesn't send the cookie the server doesn't receive it and cannot authenticated the user
Hope it helps
There's also a foible with the way PHP handles non-zero expiries on sessions; basically if you set the session cookie to expire in 15 minutes, it will expire 15 minutes from the start of the session... it won't refresh that expiry time.
To run a session that refreshes whenever the user "does something" you need to store an expiry date as a session variable and, when booting up the session, check that variable and if necessary respawn the session.
I've tried to update the expiry date in the session cookie previously, when the session is started... it led to some interesting problems.
It's highly unlikely, but it is possible, the session garbage collection lifetime is also below the lifetime of the cookie expiry. There are a load of ini variables that can deal with some of these common session problems and you can override most of them by setting them at runtime:
ini_set('session.gc_maxlifetime' 900);
ini_set('session.cookie_lifetime' 0); //ALWAYS set this to 0 - so the cookie will only expire when the browser is closed
ini_set('session.cookie_domain', '.domain.ext'); //always start with a "." if you want to cover multiple sub-domains
ini_set('session.cookie_path', '/'); //always use "/" unless you want to limit the cookie to a specific path "/admin" for instance
Personally, I'd put all the session handling stuff into a (Singleton pattern) class and deal with validation and expiry in the constructor.
I need a php code that will run a query after a specific session is going to expire,
if(!isset($_SESSION['test'])) query;
something like that but does work with session expire.
The problem you'll run into: a session doesn't just expire by itself, a session is expired on the next page load if the user waited too long. As there's no communication between browser and server between requests (user action), the server won't know if e.g. the user just closed the browser (or is doing the dishes while the website remains open).
So I guess there's nothing wrong with your code as it'll tell you if the sessin is expired on the next pageload (as long as there is a next pageload :)).
If you really need to make sure, the query runs after a session expired, I guess you'll have to save your sessions to a database and run a "cleanup"-script on each pageload to run your query and get rid of expired sessions. (e.g. save "lastUserAction" and compare that to whatever your session-limit is)
I would suggest to save the date you created the session in the database and check if the session expires like:
if($db->checkExpiredSession('test') == true) {
$db->query('...');
}
Just a thought.