3

I am developing a online quiz website in php. I've done most of it-questions get selected randomly from database one at a time, and i have the following php files:

database.php, index.php, login.php, logout.php, quiz.php, result.php.

  • When the user login,He wil be redirected to index page(home page) containing quiz and result,
  • then when user select quiz he wil be redirected to quiz.php where he can take the quiz
  • later when user click on finish, user will be redirected to home page where he can see his result,this things are working fine.

Now i want to attach a countdown timer(using minutes and seconds left) which will be continuously displayed while user is taking the quiz.

When timer expires(reaches 0)the quiz.php should appear blank and should be redirected to home page,where the user can see the result.

I have the following countdown timer code in but i am not getting how to implement it,So can someone help how to implement .

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script language ="javascript" >
        var tim;

        var min = 20;
        var sec = 60;
        var f = new Date();
        function f1() {
            f2();
            document.getElementById("starttime").innerHTML = "Your started your Exam at " + f.getHours() + ":" + f.getMinutes();


        }
        function f2() {
            if (parseInt(sec) > 0) {
                sec = parseInt(sec) - 1;
                document.getElementById("showtime").innerHTML = "Your Left Time  is :"+min+" Minutes ," + sec+" Seconds";
                tim = setTimeout("f2()", 1000);
            }
            else {
                if (parseInt(sec) == 0) {
                    min = parseInt(min) - 1;
                    if (parseInt(min) == 0) {
                        clearTimeout(tim);
                        location.href = "default5.aspx";
                    }
                    else {
                        sec = 60;
                        document.getElementById("showtime").innerHTML = "Your Left Time  is :" + min + " Minutes ," + sec + " Seconds";
                        tim = setTimeout("f2()", 1000);
                    }
                }

            }
        }
    </script>
</head>
<body onload="f1()" >
    <form id="form1" runat="server">
    <div>
      <table width="100%" align="center">
        <tr>
          <td colspan="2">
            <h2>This is head part for showing timer and all other details</h2>
          </td>
        </tr>
        <tr>
          <td>
            <div id="starttime"></div><br />
            <div id="endtime"></div><br />
            <div id="showtime"></div>
          </td>
        </tr>
        <tr>
          <td>

              <br />


          </td>

        </tr>
      </table>
      <br />


    </div>
    </form>
</body>
</html>
3
  • 1
    do you record, in the database, the datetime when the user begins the quiz? Commented Dec 19, 2017 at 8:02
  • nope,i am not recording it in database,i just need a countdown timer,where when time expires the quiz should stop. Commented Dec 19, 2017 at 8:12
  • The question says how to implement countdown timer in php yet all the code given is javascript. Without recording the start time what is to stop the user reloading the page at which point the timer begins again? Commented Dec 19, 2017 at 8:15

3 Answers 3

1

There is no need to make a timer in PHP, unless you want to use WebSocket or any other thing that will keep connnection up. All you need (any you have it partially implemented) is:

1 - Javascript timer,

var maxTime = 50000; // time in milliseconds
setTimeout(postFormFunction, maxTime)

2 - Autopost

function postFormFunction() {
    getElementById('form1').submit();
}

3 - And the last, but most important (for the real app), is to make sure that user will not cheat, so you will need to store time when your form was created, and check time when it was posted, because expirienced user will stop you JS timeout and take his unlimited time unless you check it.

I will not provide any code for this one, because it's the way of how your app designed, will you store it in DB, or use tokens, or even store data on harddrive... so I believe you'll find your way when time will came for real app ;)

Sign up to request clarification or add additional context in comments.

2 Comments

Probably, some server-side code is needed to avoid that someone just reloads the page to restart the timer
@NicoHaase, I'm not intended to write server solution for this, because its too broad, and at least required to know DB schema for example, and you may no need in DB, you can use signed tokens JWT, with set timeout in payload.
1

If you do not store the starttime in the database you could more or less accomplish the same thing using sessions. The code below invokes the countdown but you will need to modify to suit the actual code you have ~ but try running this "as is" to see the result.

<?php
    session_start();

    /* quiz.php */
    if( empty( $_SESSION['quiz'] ) )$_SESSION['quiz']=date('Y-m-d H:i:s');
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Quiz countdown</title>
        <script>
            <?php
                $start=$_SESSION['quiz'];
                $end=date('Y-m-d H:i:s', strtotime( $_SESSION['quiz'] . ' +20 minutes' ) );
                echo "
                    var date_quiz_start='$start';
                    var date_quiz_end='$end';
                    var time_quiz_end=new Date('$end').getTime();";
            ?>

            document.addEventListener('DOMContentLoaded', function(){
                (function(time){
                    var now=new Date().getTime();

                    var difference = time_quiz_end - now;

                    var days = Math.floor(difference / (1000 * 60 * 60 * 24));
                    var hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                    var minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
                    var seconds = Math.floor((difference % (1000 * 60)) / 1000);



                    t=setTimeout( arguments.callee, time );

                    if( difference <= 0 ){
                        clearTimeout( t );
                        alert('GAME OVER');
                        /* redirect user, display message, stand on one leg or whatever you need to do - quiz has finished */
                        return false;
                    }
                    document.getElementById("starttime").innerHTML=date_quiz_start;
                    document.getElementById("endtime").innerHTML=date_quiz_end;
                    document.getElementById("showtime").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
                })(1000);
            },false );
        </script>
    </head>
    <body>
        <div id='starttime'></div>
        <br />
        <div id='endtime'></div>
        <br />
        <div id='showtime'></div>
    </body>
</html>

In an effort to convince you that the session will be maintained and thus the countdown preserved between pages I put together a little single page demo that emulates multiple pages. There are 3 files to this for simplicity.

The main page ~ I called it so-quiz.php but the name is immaterial

<?php
    session_start();
    include 'quiz.inc'; // see below
?>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Quiz experiments</title>
        <script>
            <?php
                $start=$_SESSION['quiz'];
                $end=date('Y-m-d H:i:s', strtotime( $_SESSION['quiz'] . ' +'.$quizlength.' minutes' ) );
                echo "
                    var date_quiz_start='$start';
                    var date_quiz_end='$end';
                    var time_quiz_end=new Date('$end').getTime();";
            ?>
        </script>
        <script src='quiz-timer.js'></script><!-- see below -->
        <style>
            #display,#actions,#question {display:block;font-family:calibri,verdana,arial;font-size:0.9rem;box-sizing:border-box;}
            #display{margin:0 auto 1rem auto;}
            #actions{margin:1rem auto;}
            #question{color:red}
        </style>
    </head>
    <body>
        <div id='display'>
            <div id='starttime'></div>
            <div id='endtime'></div>
            <div id='showtime'></div>
        </div>
        <div id='question'>
            <?php
                echo "Display question based upon page $page";
            ?>
        </div>
        <div id='actions'>
            <input id='prev' type='button' data-page='<?php echo $page;?>' value='Previous' />
            <input id='next' type='button' data-page='<?php echo $page;?>' value='Next' />
        </div>
    </body>
</html>

The second is the included file - quiz.inc

<?php
    /* session header for quiz experiments */
    /*
        to reset use ?del=1
    */
    if( !empty( $_GET['del'] ) && !empty( $_SESSION['quiz'] ) ) {
        unset($_SESSION['quiz']);
        header('Location: so-quiz.php');
    }

    if( empty( $_SESSION['quiz'] ) ){
        $_SESSION['quiz']=date('Y-m-d H:i:s');
        $_SESSION['quizlength']=20;
    }
    $quizlength=$_SESSION['quizlength'];
    $page=filter_input( INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT );
    if( empty( $page ) ) $page=1;
?>

And finally the javascript, called quiz-timer.js

    document.addEventListener('DOMContentLoaded', function(){
        document.getElementById('next').onclick=function(e){
            location.search='page='+( parseInt( e.target.dataset.page ) + 1 )
        };
        document.getElementById('prev').onclick=function(e){
            if( parseInt( e.target.dataset.page ) > 1 ) location.search='page='+( parseInt( e.target.dataset.page ) - 1 )
        };

        (function(time){
            var now=new Date().getTime();
            var difference = time_quiz_end - now;
            var days = Math.floor(difference / (1000 * 60 * 60 * 24));
            var hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((difference % (1000 * 60)) / 1000);

            t=setTimeout( arguments.callee, time );

            if( difference <= 0 ){
                clearTimeout( t );
                alert('GAME OVER');
                /* redirect user, display message, stand on one leg or whatever you need to do - quiz has finished */
                return false;
            }

            document.getElementById("starttime").innerHTML='Quiz began at: '+date_quiz_start;
            document.getElementById("endtime").innerHTML='Quiz will end at: '+date_quiz_end;
            document.getElementById("showtime").innerHTML = 'Time remaining: '+days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
        })(1000);
    },false );

The previous,Next buttons reload the page and increment the page counter which in effect emulates different pages loading. Note that the display of time/countdown is maintained because the included quiz.inc maintains the session.

4 Comments

hey RamRaider thank you very much. This is great and the solution works well.but the issue is I have kept each questions in different php pages,when the student finishes answering first question,and click next the timer count wil again starts from beginning for next question,but i need the timer count to continuously displayed while user is taking the quiz,til the user finishes.can u please help out with this.
If each page has the same line if( empty( $_SESSION['quiz'] ) )$_SESSION['quiz']=date('Y-m-d H:i:s'); the session is maintained and hence the timer is maintained
yeah i tried it, but it is not working,the timer is restarting for each question.
I just set up a test using different pages that have the code I mentioned at the top and it works fine.
0

You can use PHP and JS to create a countdown timer. The session helps you get data on another page. Use JS an PHP and create a dynamic countdown timer as well as you can use session. Create a countdown timer using JS and PHP. I tried my self and create it.

  1. Create a database .
  2. Use strtotime() function

    var countDownDate = * 1000; var now = * 1000;

You can use the session also.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.