What happens to a SESSION when it expires in PHP or refreshes the page?

Asked

Viewed 967 times

6

What happens when Session time expires ? (This time is usually 24 minutes by default).

Example: When logging in we set the credentials of a particular user on $_SESSION, with the data resulting from a SELECT (a query) made in the database, as below:

$_SESSION["id_usuario"] = $retorno_select["id"];
$_SESSION["nome"] = $retorno_select["nome"];
$_SESSION["email"] = $retorno_select["email"];
$_SESSION['usuario'] = $retorno_select['usuario'];
$_SESSION["departamento-usuario"] = $retorno_select["departamento"];
$_SESSION['permissao'] = $retorno_select['permissao_acesso'];

So on every page I want to check the user’s access permission, or utilize some user data (like even a simple "Bom dia, $_SESSION['nome']"), i give a session_start() to start this Session.

My question is the following: when finishing this 24 minutes (SESSION’s default duration time) what happens to this data that was set ? Like this one below for example:

$_SESSION["nome"] = $retorno_select["nome"];

That one $_SESSION["nome"], and all the others that were created are destroyed ? The values that were passed to them are erased and they remain active?

What happens to SESSION if it expires and I give a F5 (refresh) on the page and that page has a session_start() ?

What happens if SESSION has a life time of 24 minutes and when it has 15 minutes I give a F5 (refresh) on the page ? Your counter will continue counting from 15 minutes or this counter will reset and start again ?

What happens when we make an AJAX request in a file .php that has a session_start() in it ? The life time of SESSION is reset ?

How do we use PHP code to increase the time of a created session ? For example, we enter a page, the session is "running" (already with a lifespan of 15 minutes) and the session has that lifespan pattern of 24 minutes. So we want to increase this lifespan from 24 minutes to 1 hour. How would we do in the page archive ? It could also be set this "default" time increase at the time we log in and fill it with user data.

After SESSION has expired (past 24 minutes), what happens, for example, if I enter a file, give a session_start() and execute one of the commands below?

session_start();

if(isset($_SESSION["nome"])){
   return true;             
}
else{
   return false;
}

Or:

session_start();

if(empty($_SESSION["nome"])){
   return true;             
}
else{
   return false;
}

Or:

session_start();

if($_SESSION["nome"]){
   return true;             
}
else{
   return false;
}
  • Thanks for the editing, @hkotsubo. I wrap myself around posting PHP codes here.

  • 1

    Ajax or normal back-end request is all HTTP, it doesn’t fully understand the difference of what happens on your front, so I explained in the reply about LOCK, indicated the link https://answall.com/a/57827/3635 and talked about it, how it will release only as another conclusion, that is, being ajax or normal, it will be HTTP and ajax will only load when the main page completes the use of the session.

2 answers

12


The session is kept in a file, what you have in the "front-end" (in the client program, as browser) is a COOKIE with a key for the session, when the SESSION exceeds the life limit the GC (https://www.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime) will consider as the file "potentially/probably" for deletion.

The GC will not eliminate exactly in such time, or disregard, it will also depend on:

This already comes with default values, but you can also configure from PHP7 with the first parameter of session_start:

session_start ([ array $options = array() ] ) : bool

You could force a session cleanup by forcing GC and then running session_destroy, like this:

<?php
session_start();

...


session_gc();
session_destroy();

But I believe that this internally is extremely laborious, besides that this can cause problems with competing connections, even if the sessions use LOCK, there is the possibility of the call taking place race condition, then really use session_destroy() or force something that is laborious internally like GC is consuming and disrupting more than necessary your own scripts.

I suggest that if you intend to prevent certain data from continuing, you could simply define a flag on its own $_SESSION referring that it must be "dead", in my situations I usually just create a key within $_SESSION to inform when was the last update and if it is out of time then I disregard it, but I will not go into detail about this, because it kind of depends on what you want to do.

There are also those who make use of the session_regenerate_id() to exchange the user’s session for a new one, but this does not invalidate the second one, to "invalidate" would be the case to use so session_regenerate_id(true), but this will also have a problem of race condition, of course no one is forbidding to use this, but it must be understood that it is problematic, off that the immediate deletion of session data also DEACTIVATES the detection and prevention of session hijacking attacks, ie more problems.

In my view the best is to control access to session by time/timestamp, because if someone accidentally accesses (or "hijacks" a COOKIE with the key of an old session) old data with the timestamp you could determine that it is invalid.

I need to highlight a detail about what is LOCK, when we are recording data in a session the file is locked, if you access multiple pages, for example 10 pages at the same time, with the same session while the first one is loading and using the session the other 9 pages will be "locked" and "loading", until the first page releases the session, then the second page will continue loading, but the other 8 pages will continue waiting, as I explained in:


The refresh on the page

The refresh on the page I think refers to the F5 or Ctrl+F5 (Cmd+F5) in most browsers, this is totally irrelevant to the session, there is no way exactly the back-end understand everything that is done in the client program (browser), the refresh is more an action in the client and not in the back-end, basically it interrupts/cancels the HTTP request and makes a similar new request, just this, the process is all HTTP, the session will continue there, PHP even understands sometimes a prior cancellation by the user through SAPI (apache, ngnix, etc) and may cancel your PHP script, but at the end of any way when your "script die" (finish) the only thing that will occur is something similar to function session_write_close(), which will record what was in the "memory", because as I explained in the previous link (about LOCK+session), the data is only recorded at the end or with session_write_close().

Even with Ajax or anything else PHP has no way of knowing exactly what happens in your client, the sessions are managed in the back end, by your scripts and by GC, in web pages almost everything is HTTP, more or less that:

  1. Browser requests
  2. Server (apache/ngnix/etc)
  3. SAPI communicates with PHP
  4. PHP processes
  5. PHP returns pro SAPI (server)
  6. Server sends reply download
  7. Browser downloads the response it is receiving

Clearing your browser cookies won’t affect anything either, because as I said before, session cookies are only for storing session keys, which takes care of eliminating idle sessions is GC, and this is something we have no control over and we should not have.

The suggestion to "invalidate" the session was the one I suggested, a flag or timestamp.

  • Thank you for the reply. Now I will clarify some points here by the comments. So from what I understood of your reply. the lifetime of a Session will always be the same, independent of F5 on the page (this does not restart the session, correct ?). If the session is with 15 minutes of life and you give an F5, then it continues with the same 15 minutes.

  • @Gambi yes, that’s what I commented, the F5 occurs on the client-side and I said: "there is no way exactly the back-end understand everything that is done in the client program (browser), refresh is another action in the client and not in the back-end", what is on the back is on the back, F5 is on the customer, so I think it became clear that a customer action can not interfere that something exclusive of the back-end. The only thing that eliminates server sessions is session_destroy or GC. Reinforcement also that is ajax or normal, is all HTTP, IE pro backend it does not tab the difference.

  • When the lifespan of the Session is over, what happens, for example, in those 3 snippets of code I put there in the question ?

  • @Gambi happens as expected, a new session will be generated and the value of ["nome"] probably won’t exist.

  • A new Session with a new life span ?

  • @Gambi of course, if it is new starts the new cycle, controlled by GC, if it is new has nothing to do with the old.

  • So here’s the thing. On every page of my system I have a session_start() at the beginning of the files. Assuming that you have spoken, in this last comment, every time I give an F5 on the page the Session’s life time will reset and start again, correct ?

  • 1

    @Gambi no, this totally wrong, session_start no Zera anything, in no time I said that Zera, do not know where it got this.... session_start only starts access to an existing session and if it does not exist it will create, it puts the session file that is in the back end in LOCK, preventing other pages to access it until it releases, the other pages are locked, everything explained in the reply.

  • 3

    @Gambi PS: if the upvote in the other answer was yours to say that the other answer could not be more wrong, and I am not saying a little wrong, this is completely wrong. I commented below, give up on wrong answers so is support for future visitors to learn wrong instead of right.

  • You mentioned this in the comment: "it happens as expected, a new session will be generated and the value of ["name"] will probably not exist.". Does "a new session is generated" not mean that a new session will be created ? In my comment, previous to yours, I had asked what would happen in the case of my 3 code snippets of the question.

  • @Gambi generated and created is the same thing here, something "generates", isn’t it? Do you understand how GC works? GC is not in your script, this out, the script is run by the script interpreter, it is fully controlled from the outside, and so I said you can even try to control GC and session_destroy, but this will cause problems race condition.

  • Taking advantage of your readiness and good will, I have made one last addition to the question, as it is a question that has haunted me for some time. If you could change, for one last time, your answer and add information about that doubt (which I believe is other people’s too), I would be grateful. I added just below the AJAX topic. About increasing the session lifecycle.

  • @Gambi this ai is very complex to answer, because there are different locations and questions of access to session, a session does not last 24min, the GC acts by idleness and of course it has life time yes, but there is a question of the cookie being deleted if the browser is deleted, but the session still exists. For me this there is material for another question, but I will see what I can answer here without leaving the giant answer

  • You’re awesome, man. you’ve already secured your place in heaven. Think that your answer will help other users who have the same question as me (even though the answer is great). I asked that question the other day, but no one was interested.

  • Speak there, nor did it give an addition to that information, yes ? The acceptance of your answer is not conditioned to this. I’m just commenting because you said that maybe it would add to the answer there.

  • 1

    @Gambi as I said, what you asked goes further, it is complicated to formulate an example, the idea of invalidating sessions I have already suggested, if I have time, in the FDS I formulate something calmly that works and is tested, there is something that is not cake recipe, it is not only suggest here, soon return with something ;)

Show 11 more comments

0

Among the options you questioned (ISSET, EMPY or IF() ). It is recommended to use if(isset($_SESSION["name"])) as the variables cease to exist, if you use EMPTY() you will be testing whether they are empty, and depending on your PHP version if($_SESSION["name"]) will not work.

If your session has expired the server will show an error message when trying to fetch the session by the id that will be registered in your browser.

The default is that F5 does not destroy the session, if this is happening in the client part, I SUGGEST it is some browser configuration. Already happened to me problem in the session because of installed plugins.

An example of how it works on a website login page.

  1. The user submits the login form, a server on the other side authenticates the request by validating the credentials.
  2. If the credentials entered by the user are valid, the server will create a new session. The server generates a unique random number, called the session ID. It also creates a new file on the server, used to store session-specific information.

  3. Then a session ID is passed back to the user along with any requested feature. Behind the scenes, this session ID is sent in the PHPSESSID cookie in the response header.

  4. When the browser receives the response from the server, it comes across the PHPSESSID cookie header. If cookies are allowed by the browser, it will save this PHPSESSID cookie, which stores the session ID passed by the server.

  5. For subsequent requests, the PHPSESSID cookie is passed back to the server. When the server finds the PHPSESSID cookie, it will attempt to initialize a session with that session ID. This is done by loading the session file that was created earlier during the session startup. Initialize the $_SESSION super global array variable with the data stored in the session file.

  • Dear Bartollo about this he said: "The default is that F5 does not destroy the session, if this is happening I suggest it is some browser setting." and since when does client-side actions directly affect files within servers? If the session is not existing it is because it has something misconfigured, because in the correct use the only way to delete the session is in the server script or it has expired as DEFINED settings. And I don’t understand why you recommended É recomendado usar if(isset($_SESSION["nome"])), the author is already using isset.

  • On web everything is HTTP, I recommend reading: https://answall.com/a/448297/3635

  • Dear Bartollo, Sessionstorage has nothing to do with PHP session.

  • Thanks for the @Guilhermenascimento reflections, I made some corrections to adjust the understanding to what I wanted to express with the text. I also altered the image!

  • This image there also has nothing to do with php session, this here refers to the "tabbed session", which has nothing to do with HTTP, only has to do with the current user account and the browser session and only. Plus this is an add-on. Besides the rest of the question is also wrong, I recommend you read the other answer and understand well how HTTP works and understand where CLIENT-SIDE and SERVER-SIDE are.

  • Thanks again @Guilhermenascimento ! I removed the image!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.