Hi guys...

I'm trying to create an examination page (in PHP) wherein I want to show to the user/examinee the remaining time.. I manually set the exam time to 1 hour (1:00:00). The problem is I want to keep that time decrementing once the examination is started..
If time become '0/(0:00:00)' it will redirect to another page to count user/examinee correct answer...

The big deal here is, I don't know how to keep that exam time decrementing.. Can anyone HELP me PLEASE ? !!! Thank's in advance.

Recommended Answers

All 10 Replies

use javascript: and apparently I google better than you but here is working script from this tuturial: http://forum.codecall.net/javascript-tutorials/22380-how-create-countdown-timer-javascript.html

<script type="text/javascript">
var Timer;
var TotalSeconds;


function CreateTimer(TimerID, Time) {
    Timer = document.getElementById(TimerID);
    TotalSeconds = Time;
    
    UpdateTimer()
    window.setTimeout("Tick()", 1000);
}

function Tick() {
    if (TotalSeconds <= 0) {
        alert("Time's up!")
        return;
    }

    TotalSeconds -= 1;
    UpdateTimer()
    window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
    var Seconds = TotalSeconds;
    
    var Days = Math.floor(Seconds / 86400);
    Seconds -= Days * 86400;

    var Hours = Math.floor(Seconds / 3600);
    Seconds -= Hours * (3600);

    var Minutes = Math.floor(Seconds / 60);
    Seconds -= Minutes * (60);


    var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)


    Timer.innerHTML = TimeStr;
}


function LeadingZero(Time) {

    return (Time < 10) ? "0" + Time : + Time;

}
</script>
<?php echo "hello world <br />"; ?>
<html>
<head>

</head>

<body onload='CreateTimer("timer", 3600)';>
<div id='timer' />

</body>
</html>

Thank's for the response ddymacek...

But I don't really understand what this below codes means:

function UpdateTimer() {
    var Seconds = TotalSeconds;
 
    var Days = Math.floor(Seconds / 86400);
    Seconds -= Days * 86400;
 
    var Hours = Math.floor(Seconds / 3600);
    Seconds -= Hours * (3600);
 
    var Minutes = Math.floor(Seconds / 60);
    Seconds -= Minutes * (60);
 
 
    var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
 
 
    Timer.innerHTML = TimeStr;
}
 
 
function LeadingZero(Time) {
 
    return (Time < 10) ? "0" + Time : + Time;
 
}

Anyway thank's for your post... I really appreciate it ..!
mmh.. Can I ask you one more question, What if examination time is being loaded from database? e.g..(examTime="01:00:00" instead of 3600)... How this codes above will react if this is the situation?? Thank's..

Member Avatar for diafol

You need to use javascript - BUT - you need to make it poll the server when a page is refreshed or changed. Otherwise the js is reset.

Also, you could trigger an ajax confirmation check every 15 minutes of so, just to ensure that the time is correct with regard to the server - although this may be overkill.

Ardav has a good point. And it depends on how it is stored in your database.
If you are pulling from a database, they may be some conversion, (I could see that maybe they have a quiz set up the same way with a 15 minute time limit, so I can see this would be useful) anyway...
in this case 1 hour = 3600 (seconds). 15 minutes = 900 (seconds).
you can get the val from the db, I'd probably use ajax and on the return you can call CreateTimer('x',time) where time is a converted time from your db.

// updates the innerHTML of 'timer' div on page
function UpdateTimer() {
	// get the total seconds 
    var Seconds = TotalSeconds;
    // there are 86400 seconds in a day, so we set the 'days left' variable here
    var Days = Math.floor(Seconds / 86400);
	// remove the days left from our seconds field
    Seconds -= Days * 86400;
	// calculate remaining number of hours :  there are 3600 seconds in an hour
    var Hours = Math.floor(Seconds / 3600);
	// remove the 'hours left' from our seconds variable
    Seconds -= Hours * (3600);
	// calculate remaining number of minutes, 60 in an hour.
    var Minutes = Math.floor(Seconds / 60);
	// finally remove the minutes from the seconds string and now
    Seconds -= Minutes * (60);

	// Days, Hours, Minutes and Seconds variables are set from above, the 'LeadingZero function'
	// if a number is less than 10 that is passed to the LeadingZero function it appends a 0 to the front (so it looks consistent and pretty)
    var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
    Timer.innerHTML = TimeStr;
}

// also change this line
<div id='timer' />
//to this:
<div id='timer' ></div>

Thank's Master ardav.

But what should I do in-order to do it? I've tried to google it, but it gives me only countdown js in which 'minutes' and 'seconds' is already specified... I don't think it will work in my situation... Can you give me a simple code PLEASE?? inorder for me to do it.. Examination time format should be like this '1:00:00' it is being loaded from database... PLEASE Help me!!! Thank's in advance...

Thank you so much for your response ddymacek... I thank you also for the codes explanation... Now I quiet understand... Based on my situation that is being mentioned, how will I use your code? or can I still use it? If don't, can you give me any simple code inorder for me to do it PLEASE.. Thank's in advance....

Yes, sometimes things are not always straight forward. here is a time conversion script, it will translate hh:mm:ss into seconds only, which the countdown timer uses:

<SCRIPT LANGUAGE="JavaScript">
function splits(string,text) {
// splits string at text
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return;
    if (i == -1) {
        splitArray[splitIndex++] = string;
        return;
    }

    splitArray[splitIndex++] = string.substring(0,i);

    if (i+txtLength < strLength)
        splits(string.substring(i+txtLength,strLength),text);

    return;
}

function split(string,text) {
    splitIndex = 0;
    splits(string,text);
}

function split(string,text) {
    splitArray = string.split(text);
    splitIndex = splitArray.length;
}

var splitIndex = 0;
var splitArray = new Array();

// Call this function, This is where you set your time, this is the field that would come back from the database.
function calculateTime(time) {
    splitIndex = 0;

    split(time,':');

    for (var i=splitIndex-1, j=1, answer=0; i>=0; i=i-1, j=j*60)
        answer += splitArray[i]*j - 0;

    // return this it is converted hh:mm:ss time value to seconds   
    //document.myForm.mySeconds.value = answer;
    return answer;
}
</SCRIPT>

you use it by calling
seconds = calculateTime(01:00:00);
in this case seconds now = 3600.

That should work for any denomination of time you have stored in your db.

Thank you so much for your code ddymacek... I very much appreciate it.... Yeah, you're right there "sometimes things are not always straight forward"... I don't know how this codes will work... but I'll figure it out... THANK YOU so much...

guess I'll throw my two cents in, though it may be a bit late. My approach would be to set the exam end timestamp in a php session var by adding the total number of seconds allocated to the test to the current time at the start of the test. I would then run an ajax call to a separate page that would subtract the current time from the session stored end time and return the value. Upon an ajax response of a negitive number the page could be redirected as desired.

here is a rough script that shows how this might look.

<? 
 
session_start();
if(!isset($_SESSION['exam_end_time'])){
//	$exam_details=mysql_fetch_assoc(mysql_query("SELECT exam_length FROM exams WHERE name='your_exam_name'"));
	//assuming the data were in the db as a number of seconds the code would be as follows for setting the end time. If the database stores it in any other fashion your will need to first convert to seconds
	$exam_details['exam_length']=60*60;//this is only here because I didn't create the database. Remove the line once the db connection is in place.
	$_SESSION['exam_end_time']=time()+$exam_details['exam_length'];
}
?>

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Exam</title>
<script>
function checkTime(){
	var ajaxRequest;
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
			}
		}
	}
	ajaxRequest.onreadystatechange=function(){
		if (ajaxRequest.readyState==4){
			document.getElementById('Timer').innerHTML=ajaxRequest.responseText
			if(ajaxRequest.responseText=="0"){
				window.location = "http://www.google.com/";//change this to your exam over page
			}
		}
	}
	ajaxRequest.open("GET","checkTime.php" ,true);
	ajaxRequest.send();
}
	int=self.setInterval("checkTime()", 1000);//run the ajax call every 1 seconds
</script>
</head>

<body>
<div id="Timer"></div>

your exam questions / form would go here. 
</body>
</html>

and then the checkTime.php page would look like this

<? 
 
session_start();


$r_time=$_SESSION['exam_end_time']-time();
if($r_time>0){
	$hours=floor($r_time/60/60);
	$minutes=floor(($r_time-($hours*60*60))/60);
	$seconds=$r_time-($hours*60*60)-($minutes*60);
	echo $hours . ":" . $minutes . ":" . $seconds;//maybe someone can find a better way to format this? 
}
else{ echo "0";}
?>

note that I only minorly debugged this script so it will still need some work in order to connect to your database and set the expiration time.

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.