Function start at session expiration?

Is it possible to run a function at session termination in a PHP script? My script asks a few questions and the user has 30 minutes to answer or the session is expiring. I would like my script to save any progress in a .txt file if the session expires and the user does not complete all the answers. How can i do this?

I heard about register_shutdown_function ('shutdown'); but I am confused by where I would call it in my script.

My current script starts as follows:

ini_set('session.gc_maxlifetime',1800); ini_set('session.gc_probability',1); ini_set('session.gc_divisor',1); session_start(); if($_SESSION['loggedin'] !== 1) {//checks to see if user has logged in header('Location: login.php'); exit;} ...asks a bunch of questions.... session_destroy(); 

Thank you for your help.

+4
source share
2 answers

You have two options:

  • Save the progress when this happens (after each answer) and save the information about whether it was completed. This solution works even if the browser is closed (progress is saved in real time).

  • Use AJAX to call the server each for example. 5 seconds, and the server should return information about the end of the session or not. If the session has ended, then do what you need in JS (even redirect to another page). This solution does not guarantee the preservation of progress (the browser may be closed before the action is completed).

You can combine both options depending on what you need and how your application works.

If you reload the page after each answer (for example, reload to display the next question), you can use the option . 1 . If all questions are on the same page, select option no. 2 . If your application is a combination of the two, you can choose both.

EDIT:

Judging by your code, you are mixing:

  • session in terms of answering questions using
  • a session in terms of storing values ​​between page requests in PHP .

The best idea is to separate them. Give the PHP session a much longer period because it is necessary for some other things, such as actually displaying progress or even saving progress. Instead, mark the start time of the test and save it in a PHP session. Thus, after the time for testing is exhausted, you can determine this and ignore any questions that were after that.

+3
source

There are several methods that immediately come to mind. You can use PHP built into the sleep method, or you can use AJAX . Not to say that these are the only paths, only the first ones that come to mind.

Edit: Now that I am thinking about this, sleep is probably not an option, as it will exceed the maximum execution time and throw an error. I did not check to make sure, but it seems logical. So AJAX is your best bet if I don't miss anything.

+1
source

Source: https://habr.com/ru/post/1380321/


All Articles