Sushmitha M
Sushmitha M

Reputation: 31

how to implement countdown timer in php

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.

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>

Upvotes: 3

Views: 11845

Answers (3)

Vishal Rana
Vishal Rana

Reputation: 63

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.

Upvotes: 0

Professor Abronsius
Professor Abronsius

Reputation: 33813

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.

Upvotes: 1

2oppin
2oppin

Reputation: 1991

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 ;)

Upvotes: 1

Related Questions