PHP:公式输入的计时器

I am coding a web based exam application in PHP.

  • The examinee has to choose a set of modules with the according questions.
  • A module is represented as one-single-formular.
  • For each module he got for example 30 minutes.

I will achive that if the 30 minutes are over, the state of the form (answered and unanswered questions will be stored in a database) and the form will be closed e.g. redirect to menu page. I tried something like that:

PHP :

<?php
    set_time_limit('30000');
    function redirect(){
      // Some Stuff
    }
    $i = 1;
    while($i <= 45){
      sleep('60');
      callthis();
      flush();
      $i++;
    }
?>

At my hoster set_time_limit couldn't be used because of PHP's Safe Mode.

What is the most reliable server-based solution (no Javascript) for a form timer in PHP?

Here's a simple method

  • generate a unique token value tied to the user account
  • store this token along with the start time in a database or session variable
  • have the token embedded in the form as a hidden field

When the form is submitted you simply need to check the token was generated in the last 30 minutes. You can implement some client side countdown as an aid to the user, but the real timing must happen on the server side.

You would need to add a few additional security checks and balances, such as ensuring a logged in user can only have one token at any one time.

You need to store the time when the test begins in a session variable or equivalent persistent method, and check the elapsed time on each form submission. (Make sure your session timeout is longer or equally long as the test duration.) You can display a static number specifying remaining time on each page reload. If you want to display a countdown, you will need to use javascript.

HTTP is a stateless protocol. This means that the flow of control for a PHP program is this:

  • User requests one of your pages
  • PHP code generates a page
  • Page is delivered to user. At this point, PHP is done running

In order to follow up, you must have something running on the user side. Namely, JavaScript. This can inform the user that their time is up. In addition, you can check the difference in times between when a form was presented to the user and when it is submitted. But this processing doesn't happen until the user returns to PHP to get another page.