Hello...
I have a quiz application based on PHP.
I use paging, which is showing only one question per page.
I want to set a time limitation on the application.
The problem is that when i do refresh the page then javascript countdown timer start from starting.
What i want to do is i want the time limitation only loaded once at the beginning. though we move to the prev or next page, the time will keep on counting without being started again.
Can you help me with this?
Many thanks for the helps....PLZZZZZZZZZZZZZZz send me changes in code so that i can deposit my project upto 3rd aug 07.
MY CODE IS::

<?php
 session_start();
 if(isset($_SESSION['counter']))
  {
   $_SESSION['counter']+=1;
   }
   else 
   {
   $flag=1;
   $_SESSION['counter']=-1;
   }
   
 ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="JavaScript" type="text/javascript">
        var hr =  00;    //<%=request.getAttribute("HR") %>
		var sec = 00;   // set the seconds
		var min =01;   // set the minutes	
  		
  		
		function countDown() {
		   sec--;
 
		   if (sec == -01)
		   {
			   sec = 59;
			   min = min - 1; 
		   }
		   else { min = min; }
 
		   if (sec<=9) 
		   { sec = "0" + sec; 
		   }
		   
		   if(min==-01)
		   {
		   		min=59;
		   		hr= hr-1;
		   }
 
		   time = (hr<=9 ? "0" + hr : hr)+" : " + (min<=9 ? "0" + min : min)+ " : " + sec ;
		   if (document.getElementById) { document.getElementById('theTime').innerHTML = time; }
		   //document.ans_form.timeLeft.value = time;
 
		   /*if (document.getElementById)
		   { 
		   		theTime.innerHTML = time; 
		   }*/
 
		   SD=window.setTimeout("countDown();", 1000);
 
   		   // To check time is over or not		   
	 if (hr=='00' && min == '00' && sec == '00') 
		   { sec = "00"; window.clearTimeout(SD); 
		   		alert("stop");
		   }
		}
		window.onload = countDown;
 
	</script>



<script language="javascript">
    //var targetURL="usermain.php"
    function doRedirect(targetURL)
    {
     window.location.replace(targetURL);
    } 	  
	</script>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style9 {
	font-size: 24px;
	font-weight: bold;
}
.style10 {
	font-size: 36px;
	font-weight: bold;
}
.style11 {color: #000066}
-->
</style>
<script language="javascript">
			  function check()
			   {
			    var checked=false;
			    for(counter = 0; counter < 4; counter++)
				 {
			    if(document.ans_form.option[counter].checked)
				 {
				   checked=true;
				 }  
				 }
				if(checked == false)
				 {
				  alert("Please select an option ");
				  }
				else document.ans_form.submit();
			}	 
			
		function check1()
		 {
		  document.ans_form.submit();
		 } 
		  	   
            </script>     
</head>

<body>
<table width="100%">
 <tr><td width="100%" align="center"><span id="theTime" class="timeClass"></span></td></tr>
</table>
<?php 
echo sec;
 if (!isset($_SESSION['userid'])) 
  { 
   ?>
   <script language="javascript">
    doRedirect("main.php");
	</script>
   <?php
    }
?>	 
<?php

$conn=mysql_connect("localhost","root","");
mysql_select_db('onlineexam', $conn);
//Write the code for random number generation
// begin the session
//..............................................>>>
 
//.........................................>	
 for($j=0; $j<11; $j++)
 {
 $x[$j] = $j+1;
 
 //for ( $i = 1; $i < 51; $i++ )
 // print "<tr><td>" . $x[$i] . "  "; 
 // $y=$x[$i];
 }shuffle($x);
 
 for($j=0; $j<=3; $j++)
 {
 $y[$j] = $j+1;
 
 //for ( $i = 1; $i < 51; $i++ )
 // print "<tr><td>" . $x[$i] . "  "; 
 // $y=$x[$i];
 }shuffle($y);
for($j=0;$j<5;$j++)
 {
  $z[$j]=$x[$j];
 }
   
if(!isset($_SESSION['k']))
 {  
 $_SESSION['k']=$z;
 }
$_SESSION['p']=$y;  
// loop through the session array with foreach
	$user_id=$_SESSION['userid'];
	$query="select count(*) from user_exam where userid='$user_id'";
 $result=mysql_query($query) or die(mysql_error());
 $row=mysql_fetch_row($result);
   if($row[0] == 0)
    {
	foreach($_SESSION['k'] as $key=>$value)
    {
    // and print out the values
    echo  $value.' <br />';
	$query="insert into user_exam(userid, attemptno, status) values('$user_id','$value', 'not')";
	$result=mysql_query($query) or die(mysql_error());
    }
	}
	$query3="select * from user_exam where userid='$user_id' and status='not'";
 $result3=mysql_query($query3);
 $row3=mysql_fetch_row($result3);
 echo $row3[0];
 if($row3 == null)
  {
   ?>
   <script language="javascript">
    doRedirect("paprfinis.php");
	</script>
    <?php
	}
	
  // Fetch the questions from database
  // $user_id=$_SESSION['userid'];
   //echo $user_id;
   // write code to count number of attempted questions in the database by a particular user
   //............
   
	
  $counter=$_SESSION['counter']; 
  if($counter == 4) $_SESSION['counter']=-1;
 echo "counter:".$counter;
 
 //$que_no=$_SESSION['k'][$counter];
 //$temp_array=$_SESSION['k'];
 //$que_no=$value;
 echo "queno:".$que_no;
 
// echo $que_no;

 //echo $_SESSION['que_no'];
  
   
  
 echo $user_id;
 $query="select * from user_exam where userid='$user_id'";
 $result=mysql_query($query) or die(mysql_error());
 mysql_data_seek($result, $counter);
 $row=mysql_fetch_row($result);
 if(strcasecmp($row[2], 'not') == 0)
    {
	 echo "question :".$row[1];
	 $result1 = mysql_query("SELECT quesdesc, opt1, opt2, opt3, opt4 FROM question_master where queno=$row[1]");
     $row1=mysql_fetch_row($result1);
	 $_SESSION['que_no']=$row[1];
	 echo "session question:".$_SESSION['que_no'];
	}

 
	
 else
  {
   ?>
   <script language="javascript">
    doRedirect("tstqus.php");
</script>
<?php
 }
	
 
 /*while($row=mysql_fetch_row($result))
  {
   if($que_no == $row[0])
    {
	 $flag=1;
    } 
  }   
if($flag != 1)
 {  */
 
 

 // echo $row[0].$row[1].$row[2].$row[3].$row[4];
 //$result1 = mysql_query("SELECT opt1,opt2,opt3,opt4 FROM question_master where queno=");
 //$row1=mysql_fetch_row($result1);
//echo $row1[0].$row1[1];*/
  ?>

<table width="916" border="0" cellpadding="0" cellspacing="0">
  <!--DWLayoutTable-->
  <tr>
    <td width="229" rowspan="2" valign="top"><img src="images/CSC.jpg" width="202" height="66" alt="jj" /></td>
    <td width="49" height="48">&nbsp;</td>
    <td width="63">&nbsp;</td>
    <td colspan="3" valign="top"><div align="center"><u><span class="style10">ONLINE EXAMINATION </span></u><span class="style10"></span></div></td>
    <td width="123"></td>
    <td width="23"></td>
  </tr>
  <tr>
    <td height="18"></td>
    <td></td>
    <td width="146"></td>
    <td width="156"></td>
    <td width="127"></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td height="14"></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td height="27"></td>
    <td></td>
    <td></td>
    <td></td>
    <td valign="top"><span class="style9"><u><span class="style11">TEST PAPER</span>:</u></span></td>
    <td>&nbsp;</td>
    <td></td>
    <td></td>
  </tr>
  
  <tr>
    <td height="17"></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td height="15"></td>
    <td></td>
    <td colspan="5" rowspan="9" valign="top">
      <form name="ans_form" action="submitqus.php" method="post">
      
      <table width="100%" border="0" cellpadding="0" cellspacing="0">
        <!--DWLayoutTable-->
        <tr>
          <td width="32" height="9"></td>
            <td width="17"></td>
            <td width="24"></td>
            <td width="20"></td>
            <td width="100"></td>
            <td width="51"></td>
            <td width="94"></td>
            <td width="16"></td>
            <td width="45"></td>
            <td width="205"></td>
            <td width="11"></td>
          </tr>
        <tr>
          <td colspan="2" rowspan="2" valign="top"><span class="style9">Qus:</span></td>
            <td height="6"></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
        </tr>
        <tr>
          <td colspan="8" rowspan="2" valign="top">&nbsp;&nbsp;&nbsp;&nbsp;<?php echo "<font face=arial size=3>". $row1[0]; ?><p>&nbsp;</p></td>
        <td height="20"></td>
          </tr>
        <tr>
          <td height="68">&nbsp;</td>
          <td>&nbsp;</td>
          <td></td>
        </tr>
        
        
        
        
        <tr>
          <td height="20">&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        
        <tr>
          <td height="20"></td>
            <td colspan="2" valign="top"><label>
              <input type="radio" name="option" id="radio" value="<?php echo $row1[$y[1]]; ?>" />
            </label></td>
        <td colspan="5" rowspan="2" valign="top"><?php echo "<font face=verdana size=3>".$row1[$y[1]]; ?>&nbsp;</td>
        <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        <tr>
          <td height="12"></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
        <tr>
          <td height="16"></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
        <tr>
          <td height="20"></td>
            <td colspan="2" valign="top">
              <label>
              <input type="radio" name="option" id="radio2" value="<?php echo $row1[$y[2]]; ?>" />
              </label>              </td>
            <td colspan="5" rowspan="2" valign="top"><?php echo "<font face=verdana size=3>".$row1[$y[2]]; ?>&nbsp;</td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
        <tr>
          <td height="12"></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
        <tr>
          <td height="19"></td>
            <td>&nbsp;</td>
            <td></td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
        <tr>
          <td height="20"></td>
            <td colspan="2" valign="top">
              <label>
              <input type="radio" name="option" id="radio3" value="<?php echo $row1[$y[3]]; ?>" />
              </label>              </td>
            <td colspan="5" rowspan="2" valign="top"><?php echo "<font face=verdana size=3>".$row1[$y[3]]; ?>&nbsp;</td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
        <tr>
          <td height="12"></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
        <tr>
          <td height="15"></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
        <tr>
          <td height="20"></td>
            <td colspan="2" valign="top">
              <label>
              <input type="radio" name="option" id="radio4" value="<?php echo $row1[$y[0]]; ?>" />
              </label>              </td>
            <td colspan="5" rowspan="2" valign="top"><?php echo "<font face=verdana size=3>".$row1[$y[0]]; ?>&nbsp;</td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
        <tr>
          <td height="12"></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
        <tr>
          <td height="13"></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
        <tr>
          <td height="19"></td>
          
          <td colspan="3" rowspan="2" valign="top"><a href="tstqus.php"><input name="BACK" type="submit" class="style11" value="BACK" /></a></td>
          <td></td>
          <td valign="top"><input name="SUBMIT1" type="button" value="SUBMIT" class="style11"  onclick="check();"/></td>
          <td>&nbsp;</td>
          
            
          </td>
          <td><input type="button" value="NEXT" name="NEXT" class="style11" onclick="check1();" /></a></td>
          <tr>
          
          </tr>
          <td></td>
        </tr>
        <tr>
       <td height="14"></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
        </tr>
        </table>
    </form></td>
    <td><!--DWLayoutEmptyCell-->&nbsp;</td>
  </tr>
  
  <tr>
    <td height="37" valign="top"><a href="Org.php"><img src="Images/Orga.jpg" alt="bvnbvn" width="177" height="31" hspace="7" vspace="2" border="1" /></a></td>
    <td></td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td height="15"></td>
    <td></td>
    <td></td>
  </tr>
  
  <tr>
    <td height="37" valign="top"><a href="Onlinetest.php"><img src="Images/onlinetest.jpg" alt="mm" width="177" height="31" hspace="7" vspace="2" border="1" /></a></td>
    <td></td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td height="19">&nbsp;</td>
    <td></td>
    <td>&nbsp;</td>
  </tr>
  
  <tr>
    <td height="37" valign="top"><a href="review.php"><img src="Images/Logout.jpg" alt="bnb" width="177" height="31" hspace="7" vspace="2" border="1" /></a></td>
    <td></td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td height="15"></td>
    <td></td>
    <td></td>
  </tr>
  
  <tr>
    <td height="37" valign="top"><a href="main.php"><img src="Images/Home.jpg" alt="bnbv" width="177" height="31" hspace="7" vspace="2" border="1" /></a></td>
    <td></td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td height="140">&nbsp;</td>
    <td></td>
    <td>&nbsp;</td>
  </tr>
  <tr><td height="37" valign="top"><a href="paprfinis.php"><img src="Images/endtst.jpg" alt="bvnbvn" width="90" height="21" hspace="7" vspace="2" border="1" /></a></td></tr>
  <tr>
    <td height="83">&nbsp;</td>
    <td></td>
    <td></td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>


  <tr>
    <td height="66" valign="top"><img src="Images/CSC.jpg" alt="df" width="202" height="66" /></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td height="3"></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>
 
</body>
</html>

Dani AI

Generated

A reliable fix is to keep the authoritative time on the server and only use JavaScript for the visible countdown. That prevents a page refresh from restarting the clock and lets the server accept or reject answers based on actual elapsed time. This directly addresses 's reset-on-refresh problem, while acknowledging 's point that client-side behavior and network issues make pure-JS timing unfair unless the server enforces limits.

Implementation summary (minimal example)

  1. Record the exam start time on first access (session or database).
  2. On every page request compute remaining seconds server-side and render that number into the page for the client display.
  3. On every submit (or finish) the server re-checks elapsed time and refuses/marks late submissions if the allowed duration passed.
  4. Use client JS only to decrement the server-provided remaining seconds and optionally auto-submit when it hits zero.

Example snippets (illustrative):

<?php
session_start();
$duration = 60 * 10; // seconds
if (!isset($_SESSION['exam_started_at'])) {
    $_SESSION['exam_started_at'] = time();
}
$elapsed = time() - $_SESSION['exam_started_at'];
$remaining = max(0, $duration - $elapsed);
if ($remaining <= 0) { header('Location: finish.php'); exit; }
?>
<script>
var remainingSeconds = <?php echo $remaining; ?>;
</script>
<script>
function startCountdown(seconds) {
  var s = seconds, el = document.getElementById('theTime');
  var t = setInterval(function(){
    if (s <= 0) { clearInterval(t); window.location='finish.php?expired=1'; return; }
    var mm = Math.floor(s/60), ss = s%60;
    el.textContent = (mm<10?'0':'')+mm+' : '+(ss<10?'0':'')+ss;
    s--;
  },1000);
}
startCountdown(remainingSeconds);
</script>

Hardening and practical notes

  • Always re-check time server-side in the submit handler and reject late answers.
  • Send no-cache headers so browser/back/refresh don’t re-use a cached page.
  • If sessions/cookies may be lost, persist the start timestamp in a database row keyed by user+exam and read it each request.
  • Log timestamps (page loads, submissions) to aid dispute resolution; network outages can’t be eliminated, so logs let an instructor handle edge cases.
  • Treat client-side JS as UX only; never as the single truth.

Recommended Answers

All 2 Replies

I don't think you can do that, unless you can store the elapsed time in a cookie.

For security reasons, you should not have control over the user's refresh, forward, and back buttons.

I just realized the utter impossibility of doing this and making it fair.

You do not have control over the following:
- The browser the student has.
- The Internet Service Provider the student subscribes to.
- Whether the ISP burdens users with popups in exchange for free or low-cost service.
- Security settings.
- Firewalls.
- Traffic loading on the ISP.

So I can see some problems:

- The page stops loading in the middle, but the timer starts.

- The page loads, but JavaScript is turned off.

- The page loads except for the script.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.