Keep the session alive even if the browser closed [duplicate] - php

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.

Related

Access session value after closing window in php

How is it possible to access a session value after the Browser window was closed in PHP?
Session variable will expires once a browser is closed. If you still want the session variable you should use cookies for that. Store the session values in cookies and access the cookie whenever you need. set session.cookie_lifetime to non-zero so that cookie will not expire. For more details about storing and accessing cookies refer php cookies and php session cookie
Use a keep alive:
Ex:
session_start();
$_SESSION["timeout"] = time();
//if 100 seconds have passed since creating session delete it. Use math to figure out minutes and hours
if(time() - $_SESSION["timeout"] > 100){
unset($_SESSION["timeout"];
}
However this may answer your question but its not always a good option.
Your Server Keeps Sessions In Memory and Too Many Can Cause Your Server To Slow Some.
If you want to keep Information About Login Even After Browser Close Use Cookies
setcookie("email-","dummytext",time()-60*60*24*365,str_replace(".","_",$_SERVER['SERVER_NAME']),0);
check out setcookie();
now to check for said cookie beginning of page
if(!empty($_COOKIE['email-'.str_replace(".","_",$_SERVER['SERVER_NAME'])]) // checks for cookie email-
http://php.net/manual/en/function.setcookie.php

What keeps a php session alive?

Are sessions only kept alive each time you access a page with session_start(); or do other pages keep it alive too?
Example (with 30 minute timeout):
1
user accesses page with session_start();
25 mins later they access another session_start();
page session stays alive
2
user accesses page with session_start();
25 mins later they access a non-session_start(); page
session stays alive
Is 2 also true ?
There is always a session cookie set in your browser whenever you access a page which has session_start(). The cookie name will PHPSESSID if the website is using PHP(although the name can be changed). This session cookie contains a session id which helps the browser to maintain that session with the server.
You can check manually by browsing any website which has your session and then delete your browser cookies, your session will be lost.
In your case both 1 & 2 are correct.
2 is correct because the user already has accessed a page which has session_start() and your session id will be set for the next 30 mins and it will be present even if you accesse a page which does not have a session.
NOTE: But the page which you will be visiting if contains session_destroy(), your session will be destroyed.
Calling session_start() merely gives your code access to the session.
What keeps the session alive is your browser sending the session id (stored in a cookie) to the server, whether you use it or not.
Answer: They are both true.
Here's the relevant part from the documentation
When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.
http://www.php.net/manual/en/intro.session.php
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
http://www.php.net/manual/en/function.session-start.php
This means if you don't call session_start, the session will not be resumed and the expiration is not extended.
The session_start() is internal mechanism for php to access session and also to send session cookie to client browser.
Case 1 is true: because user accessed a page with session_start() and then another similar page.
Case 2 is only true if the session timeout is greater than 25 minutes between two visits.
In Case 2, the server will not send any session cookie, its a browser that includes cookie in the request header.
In the instant case the PHP session life of 30 minutes is kind of a "trick question" factor. The default and almost universal session life is 1440 seconds, or 24 minutes. So for most folks, the session data could have disappeared before the 25 minute mark.
This article tells some of the detail behind how PHP sessions work.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11909-PHP-Sessions-Simpler-Than-You-May-Think.html
It doesnt have to do anything with the web pages, session interact with your browser by session id.
The session IDs generated by PHP are unique, random, and almost impossible to guess, making it very
hard for an attacker to access or change the session data. Furthermore, because the session data is stored
on the server, it doesn ’ t have to be sent with each browser request.
To start a PHP session in your script, you simply call the session_
start() function. If this is a new session, this function generates a unique SID for the session and sends it to the browser as a cookie called PHPSESSID (by default).
However, if the browser has sent a PHPSESSID
cookie to the server because a session already exists, session_start() uses this existing session:
session_start();
If you want sessions' on all of your pages, session_start() should be called on all of your pages.
Hence, 1 is CORRECT and 2 is CORRECT

When does a PHP session end?

I can't seem to find a definitive answer on the internet, so I'm asking here.
When one uses session_start(); in a .php script and saves some values, when does the session end? So when would those values not be accessible again?
I've found that refreshing the page or stopping the session code-wise would stop it, and a possible time-out would stop the session as well. But what about navigating away from the site and returning a minute later? And closing the browser?
As for the last one, on mobile, what does 'closing the browser' mean? Closing the tab or even minimalising the site?
If your session values are not linked to any cookie, the session will end when the windows browser will be closed.
If your session variable comes from a cookie, the session will end after time specified in the cookie file.
In PHP, sessions work with a cookie of type session. Server-side, the session information is constantly deleted.
To set the lifetime of a cookie in php, you can use the function session_set_cookie_params, before the session_start:
session_set_cookie_params(3600,"/");
session_start();
For ex, 3600 seconds is a one hour, for 2 hours 3600*2 = 7200.
But it's a session cookie, the browser can make it expire by himself, if you want to save longer sessions (like remember login), you need save the data in the server and a standard cookie on the client side.
Navigating away from a site when using cookies will not break the session.
There are two things that can effectively end a session:
The cookie linking it to the browser gets destroyed. PHP typically uses session cookies. These are deleted when the browser is closed. The browser, not the tab. They can also be deleted manually.
When the server hasn't received a request from the browser with the session cookie for the session for a certain amount of time (defined in session.gc_maxlifetime) and it cleans up the session data.

Running a long term session and garbage collection in PHP

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?

Destroy or unset session when user close the browser without clicking on logout [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I expire a PHP session after 30 minutes?
I am destroying all session var in logout.php and calling it when user click on logout, what is user does not click on logout.php but directly close the browser. how can i delete session then???
You can set an expiration time for the session data, test it with each session_start call and destroy the session if it’s expired:
session_start();
if (!isset($_SESSION['EXPIRES']) || $_SESSION['EXPIRES'] < time()+3600) {
session_destroy();
$_SESSION = array();
}
$_SESSION['EXPIRES'] = time() + 3600;
You cannot. However, session cookies are usually sent without an expire time which means they are deleted when the browser is closed, so the session is lost anyway.
PHP sessions should automatically expire when the browser window closes providing you do not modify the Session Cookies expiration time. If this is not happening then I would assume that you have modified this in some way and we would require further details to assist.
The session can be set to simply expire the server doesn't hear from the client after a certain period of time. That's the direction you want to be looking in...
Martin
If you do not set an expire time for the session cookie, it will be deleted when the user closes the browser, which has the same effect for most practical purposes (unless you are worried about storage or security). If that is not good enough, you could set sessions to expire very quickly and periodically refresh them via AJAX.

Categories