Is it possible to run a function when the session ends on a PHP script? My script asks several questions and the user has 30 minutes to answer or the session expires. I would like my script to save any progress to a .txt file if the session expires and the user has not completed all the answers. How would I go about doing this?
I heard about register_shutdown_function('shutdown'); but I'm confused on where I would call it in my script.
My current script starts like this:
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();
Thanks for your help.
You have actually two options:
Save the progress when it happens (after every answer) and save information whether it has been completed. This solution works even if the browser has been closed (the progress is saved in real time).
Use AJAX to call the server every eg. 5 seconds and server should return information whether the session ended or not. If session ended, then do in JS what you need (even redirect to different page). This solution does not ensure saving the progress (the browser may be closed before action is made).
You can combine both options, depending on what you need and how your application works.
If page reloads after every answer (eg. reloads to show next question), then you can use option no. 1. If all the questions are on one page, choose option no. 2. If your application is combination of the two, you can choose both options.
EDIT:
Judging from your code, you are mixing:
The best idea is to separate the two. Give PHP session a much larger time limit, because it is needed for some other things such as actually showing progress or even saving progress. Instead, mark the time when the test began and store it in PHP session. This way after the time for the test is exhausted, you will be able to determine that and ignore any questions answered after that.
There's a couple of methods that come to mind immediately. You could use PHP's built in sleep method or you could use AJAX. Not saying these are the only ways, just the first ones that come to mind.
Edit: Now that I think about it, sleep probably isn't an option as it would exceed maximum run time and throw an error. Haven't tested to make sure, but seems logical. So AJAX is your best bet, assuming I'm not missing anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With