Access session value after closing window in php - 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

Related

What is the Working Flow of Session and Cookies together

I have many doubts on cookies and session
1) can anyone explain me work flow of cookies and session together(example if I visit any site and then login by my email and password then how cookies and session work together)
2) if cookies is set for 5 minutes and session is set for 10 minutes what will happen
3) how flow will work if cookies is disabled in my computer.
There are many questions which cover your doubts already, I'll link some below. I'll answer your specific questions first:
1) When you visit a website for the first time, actually when you do a session_start() on the PHP side, a new session ID is generated (a random string) and sent to the browser as cookie, usually with the name PHPSESSID, so next time you visit the site the same data is loaded back from the session file (which is stored somewhere on the server)
2) If cookie expires before the session the browser won't send the PHPSESSID value, thus a new session ID is generated. It is usually advisable to use an expire time for cookies way longer. When you expire a cookie, you rely on the client's browser to honor your disposition, but to be safe you must expire the session server side.
3) Sessions won't work, every time the client requests a page a new session cookie will be generated
Some more information:
cookies vs session
Cache VS Session VS cookies?
What is the difference between a Session and a Cookie?

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

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.

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.

How to restore a PHP session?

I understand that PHP stores a user's session id in a cookie called "PHPSESSID" which is stored in the client's browser and is matched against the session on the server to be able to relate the 2. After closing the browser
the session info dissapears but the cookie on the client remains. Is it possible to use this cookie to restore the old session? Or does all the session data get deleted from the server the moment the client closes their browser?
I had this on my page first:
session_start();
$_SESSION['message'] = 'Hello';
echo $_SESSION['message']; // outputs hello
then I changed the page to:
$old_session = session_id();
session_id($old_session);
session_start();
echo $_SESSION['message'];
Then I closed the browser and reopened it to this page and got these errors:
Warning: session_start() [function.session-start]: The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' in C:\xampp\htdocs\localhost\test.php on line 5
Notice: Undefined index: message in C:\xampp\htdocs\localhost\test.php on line 7
How exactly does one retrieve old session info after closing the browser, is it even possible?
The accepted answer here should not be accepted. You most certainly can recover a session so long as it has not been cleared yet. It really is this simple.
<?php
session_id($the_id_of_the_session_you_want_to_reopen);
session_start();
?>
I found the answer here.
A session does exactly what it says on the tin - exists for the duration of the client's session. A browsing session by definition (such as there is one) ends when you close the browser.
Cookie-based sessions work by setting a cookie that has a lifetime defined in PHP as 0 - this means that the browser should destroy the cookie when the browser is closed. Once the cookie has been destroyed, the session ID is not sent in any subsequent server requests, so the session data will not be available in your PHP script.
However, the session data is not destroyed at the server side at the moment the user closes the browser, as you suggested - this is impossible, because the client does not notify the server that it has been closed. Instead, the session data at the server side has a TTL (time-to-live) which has a default value of 15 minutes. After this has expired, the data may be deleted at any time by the session garbage collector. In theory this could be some considerable time, but in practice on a busy server the data will be deleted within a couple of minutes of the TTL expiring.
However, PHP cannot make the session data available unless it has the session ID, and it will not have the session ID if the cookie has been destroyed, which as I say, should happen when the user closes their browser.
So the short answer to the question How can I restore a PHP session? is: You can't
This may or may not be an answer you are looking for.
As far as I know, you can't "restore" a session based on the session cookie. What I do is store a cookie with the client's id, username, and password, salted and hashed. I also store another with their id. I check for both cookies when they visit the site, then validate them against each other, then log them in automatically. While this doesn't "restore" their session, it allows them to stay logged in on my site when if they closed the browser. This was how I figured to do it, and I figure if someone did hijack or view another user's cookies, it would be near impossible to decrypt with the salt I used. The only information they would gain is the user's id.
session_start set's a cookie.
the cookie has a param cookie-lifetime
by default the cookie lifetime is set to 0
0 means until browser closed

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