Jump to content
xisto Community
doctor

How To Create An Online Timed Test With PHP? Can we do a online test with a counter(from 20 second) php for a php-n

Recommended Posts

So your trivia questionsmust be answered within 20 sec.

 

At page YY:

Ask question + register start time

-Make sure a JS refreshes after 20 sec to page XX.

-And make sure answers are posted to page XX.

 

Page XX checks for an correct answer AND checks if the registered start time in php is within the 20 sec (JS can be easily disabled and needs double checking)

 

Thanks, i do something like that with no goods results in the timer, so i follow your advice and redirect to XX page and THAT'S IT :(.

 

I will post all the code tomorrow.

 

CLICK HERE TO PLAY TRIVIA

 

Best regards,

Share this post


Link to post
Share on other sites

Well, as i promised in my last post yesterday here is the code of the script, it is not complete yet because i will make some improvements but the basical functioning is complete. Today is my happybirthday so i only post the database tables and the config files:

 

DB Tables Files:

 

CREATE TABLE registration (

id int(10) unsigned NOT NULL auto_increment,

name varchar(45) NOT NULL default '',

email varchar(100) NOT NULL default '',

nickname varchar(15) NOT NULL default '',

password varchar(32) NOT NULL default '',

is_activated char(1) NOT NULL default '0',

activation_code varchar(25) NOT NULL default '',

regdate date NOT NULL default '0000-00-00',

last_login date NOT NULL default '0000-00-00',

test_day tinyint(1) unsigned NOT NULL default '0',

points int(10) NOT NULL default '0',

PRIMARY KEY (id)

) TYPE=MyISAM COMMENT='Trivia Users';

 

 

CREATE TABLE question (

id smallint(5) unsigned NOT NULL auto_increment,

question varchar(255) NOT NULL default '',

PRIMARY KEY (id)

) TYPE=MyISAM COMMENT='Trivia Questions';

 

CREATE TABLE answer (

idq smallint(5) unsigned NOT NULL default '1',

id tinyint(3) unsigned NOT NULL auto_increment,

answer varchar(255) NOT NULL default '',

correct tinyint(1) unsigned NOT NULL default '0',

PRIMARY KEY (idq,id)

) TYPE=MyISAM COMMENT='Trivia Answers' ;

 

config.php: general configuration file

<?php$db_user = "your_db_user"; $db_password = "your_db_userpassword";$database = "your_db";$server = "localhost";$questions_test=5; // number of questions per test$total_tests=5; // number of tests per day// connect to servermysql_connect($server, $db_user, $db_password) or die ("Could not connect to the Server!" . mysql_errno() . ": " . mysql_error() );// select databasemysql_select_db($database) or die ("Could not select the Database!" . mysql_errno() . ": " . mysql_error() );include('check_login.php');?>

check_login.php: user checking configuration file
<?php/* check login script, included in config.php. */session_start();if (!isset($_SESSION['nickname']) || !isset($_SESSION['password'])) {	$logged_in = 0;	return;} else {	// remember, $_SESSION['password'] will be encrypted.	if(!get_magic_quotes_gpc()) {		$_SESSION['nickname'] = addslashes($_SESSION['nickname']);	}	// addslashes to session username before using in a query.	$pass=mysql_query("SELECT password FROM registration WHERE nickname='".$_SESSION['nickname']."'");	if(mysql_num_rows($pass) != 1) { 		$logged_in = 0;		unset($_SESSION['nickname']);		unset($_SESSION['password']);		// kill incorrect session variables.	  } 	$db_pass = mysql_fetch_array($pass);	// now we have encrypted pass from DB in 	//$db_pass['password'], stripslashes() just incase:	$db_pass['password'] = stripslashes($db_pass['password']); 	$_SESSION['password'] = stripslashes($_SESSION['password']);	//compare:	if($_SESSION['password'] == $db_pass['password']) { 		// valid password for username		$logged_in = 1; // they have correct info in session variables.	} else {		$logged_in = 0;		unset($_SESSION['nickname']);		unset($_SESSION['password']);		// kill incorrect session variables.	}}// clean upunset($db_pass['password']);$_SESSION['nickname'] = stripslashes($_SESSION['nickname']);?>

To be continued...

 

Best regards,

Edited by TavoxPeru (see edit history)

Share this post


Link to post
Share on other sites

login.php: trivia's login file.

<?phprequire 'config.php';if($logged_in == 1) {	die('You are already logged in, '.$_SESSION['nickname'].'. <a href="logout.php">Click here to logout</a>.');}?><html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>Trivia - Login</title><style type="text/css"><!--body { margin:10;background-color:#131313; font-family:Verdana, Arial; font-weight:bold; font-size:9px; color:#FFFFFF; }.register_box { border: 1px solid #323232; background-color: #202020; font-family: Verdana, Arial; font-weight: bold; font-size: 9px; color: #FFFFFF; } P { font-family:Verdana, Arial; font-size:11px; color:white; text-align:justify }background-color: #009900; cursor: pointer; }.legend {font-family: Verdana, Arial; font-size:8pt; font-weight:bold; color:white; width:50%; text-align:right; padding-left:2px; padding-bottom:3px; padding-top:3px }.title { font-family: Verdana, Arial; font-size:14pt; font-weight:bolder; color:white; text-align:center; width:100%; padding:10px }.field {font-family: Verdana, Arial; font-size:8pt; color:white; text-align:left; width:50%; padding-left:2px;	padding-right:2px; padding-bottom:3px; padding-top:3px }//--></style></head><body><?phpif (isset($_POST['submit'])) { // if form has been submitted	/* check they filled in what they were supposed to and authenticate */	if(!$_POST['nname'] || !$_POST['passwd']) {		die('You did not fill in a required field.');	}	// authenticate.	if (!get_magic_quotes_gpc()) {		$_POST['nname'] = addslashes($_POST['nname']);	}	$Sqlcheck="SELECT nickname, password, last_login, test_day FROM registration WHERE nickname='" . $_POST["nname"] . "'";	$check=mysql_query($Sqlcheck) or die(mysql_error());	if(mysql_num_rows($check)<1) { 		die("That nickname does not exist in our database. Please <a href=\"registration.php\">click here</a> to register and try again");	} 	$info = mysql_fetch_array($check);	// check passwords match	$_POST['passwd'] = stripslashes($_POST['passwd']);	$info['password'] = stripslashes($info['password']);	$_POST['passwd'] = md5($_POST['passwd']);	if ($_POST['passwd'] != $info['password']) {		die('Incorrect password, please try again.');	}	// if we get here username and password are correct, 	// check last login date and set last login date, number of plays  	// update database and register session variables.	$date=date("Y-m-d",strtotime("now"));	$times_play=0; //number of tests played today	$last=$date; // default last login date	$last_login_date = $info['last_login']; // user's last login date	if($last_login_date == $date) {		$times_play=$info['test_day'];		$last = $last_login_date;	}	$update_login = "UPDATE registration SET last_login =now(), test_day=".$times_play. " WHERE nickname = '".$_POST['nname']."'";	mysql_query($update_login) or die(mysql_error());	$_POST['nname'] = stripslashes($_POST['nname']);	$_SESSION['nickname'] = $_POST['nname'];	$_SESSION['password'] = $_POST['passwd'];	$_SESSION['tests_count'] = $times_play;	mysql_close();	// check number of test played by the user	if ($_SESSION['tests_count']==5) {		$template = "template4.html";		if(!$output = file($template)) die("Couldn't open the template file ($template). Please check and make sure that this file is where it's supposed to be.");		$output = implode("\n", $output);		$output = str_replace("%%NICKNAME%%", $_SESSION['nickname'], $output);		echo $output;		exit();	}?><h1>Logged in</h1><p>Welcome back <?php echo $_SESSION['nickname']; ?>, you are logged in and ready to play our <a href="trivia.php">TRIVIA</a>.<br /><br /><a href="logout.php">Click here to logout</a>.</p><?php} else {	// if form hasn't been submitted?><div align="center">	<center>		<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">			<table align="center" border="0" width="60%" cellspacing="0" cellpadding="0">				<tr>					<td colspan="2" class="title">LOGIN</td>				</tr>				<tr>					<td class="legend">Nickname</td>					<td class="field"><input class="register_box" TYPE="TEXT" NAME="nname" SIZE="10" MAXLENGTH="15" tabindex="1"></td>				</tr>				<tr>					<td class="legend">Password</td>					<td class="field"><input class="register_box" TYPE="PASSWORD" NAME="passwd" SIZE="10" MAXLENGTH="32" tabindex="2"></td>				</tr>				<tr>					<td width="100%" colspan="2" align="center" style="padding-top:3px;padding-bottom:3px">					<input class="register_box" type="submit" value="Login" name="submit" tabindex="3" > 					<input class="register_box" type="reset"  value="Reset" tabindex="4">					</td>				</tr>			</table>		</form>	</center></div></body></html><?php}?>
trivia.php: The Trivia's main file where we show the questions and its corresponding result using a simple html template file that include a script in javascript to control the time.
<?phprequire("config.php"); if ($logged_in == 0) {	die('Sorry you are not logged in, this area is restricted to registered members. <a href="login.php">Click here</a> to log in.');}# check number of plays per dayif ($_SESSION['tests_count']==5) {	$template = "template5.html";	if(!$output = file($template)) die("Couldn't open the template file ($template). Please check and make sure that this file is where it's supposed to be.");	$resultoutput="";	$formoutput="";	$output = implode("\n", $output);	$output = str_replace("%%RESULT%%", $resultoutput, $output);	$output = str_replace("%%NICKNAME%%", $_SESSION['nickname'], $output);	$output = str_replace("%%FORM%%", $formoutput, $output);	echo $output;	exit();}# check number of questions per playif (!isset($_SESSION['questions_count'])) {	$_SESSION['questions_count']=1;} else {	if($_SESSION['questions_count']<$questions_test) {		$_SESSION['questions_count']++;	}	else {		unset($_SESSION['questions_count']);		$update_login = "UPDATE registration SET test_day=test_day+1 WHERE nickname = '".$_SESSION['nickname']."'";		mysql_query($update_login) or die(mysql_error());		$SqlTestcheck="SELECT test_day FROM registration WHERE nickname='" . $_SESSION["nickname"] . "'";		$Testcheck=mysql_query($SqlTestcheck) or die(mysql_error());		$Testinfo = mysql_fetch_array($Testcheck);		$_SESSION['tests_count'] = $Testinfo["test_day"];		$template = "template3.html";		if(!$output = file($template)) die("Couldn't open the template file ($template). Please check and make sure that this file is where it's supposed to be.");		$resultoutput="";		$formoutput="";		$output = implode("\n", $output);		$output = str_replace("%%RESULT%%", $resultoutput, $output);		$output = str_replace("%%NICKNAME%%", $_SESSION['nickname'], $output);		$output = str_replace("%%PLAYSLEFT%%", ($total_tests - $_SESSION['tests_count']), $output);		$output = str_replace("%%FORM%%", $formoutput, $output);		echo $output;		mysql_close();		exit();	}}#$template is the template file the script will use to#format the form. $template = "formtemplate.html";#load the template fileif(!$output = file($template))  die("Couldn't open the template file ($template). Please check and make sure that this file is where it's supposed to be.");$output = implode("\n", $output);#calculate number of questions in the database$SqlTotalQuestions=mysql_query("select max(id) as total from question");$RowTotalQuestions=mysql_fetch_array($SqlTotalQuestions);$TotalQuestions=$RowTotalQuestions["total"];#Pick a random question$RandomQuestion=rand(1,$TotalQuestions);$SqlQuestionSelected=mysql_query("select id, question from question where id=$RandomQuestion") 	or die ("Error... Cant select a valid question");#populate the random question$RowQuestionSelected=mysql_fetch_array($SqlQuestionSelected);$TheQuestion = htmlspecialchars($RowQuestionSelected["question"]);$IdTheQuestion = $RowQuestionSelected["id"];#select/populate choices array$SqlA = "SELECT * from answer where answer.idq=$IdTheQuestion";$regA=mysql_query($SqlA) or die(mysql_error());$j=0;while($Answers = mysql_fetch_array($regA) ) {	$IdChoices[$j]=$Answers["id"];	$Choices[$j]=$Answers["answer"];	$j++;}#build form output for CHOICES$nChoices=sizeof($Choices);$choiceoutput="";$Text="";for($i=0; $i<$nChoices; $i++) {	$Text='<input type="radio" name="answer" value="' . $IdChoices[$i] . '"';	if($i==0) {		$First=" CHECKED ";		$Text.=$First;	}	$Text.=">  ". $Choices[$i] . "</input>";	$choiceoutput.= $Text."<br />";}#close the database connection, we just dont need anymoremysql_close();$time = time();$formoutput ="<input type=\"hidden\" name=\"question\" value=\"" . $TheQuestion . "\">";$formoutput .="<input type=\"hidden\" name=\"idquestion\" value=\"" . $IdTheQuestion . "\">";$formoutput .="<input type=\"hidden\" name=\"time\" value=\"" . $time . "\">";$formoutput .= $choiceoutput;$resultoutput=($_REQUEST["resultoutput"]=="") ? "" : $_REQUEST["resultoutput"];$output = str_replace("%%RESULT%%", $resultoutput, $output);$output = str_replace("%%NUMQUESTION%%", $_SESSION['questions_count'], $output);$output = str_replace("%%QUESTION%%", $TheQuestion, $output);$output = str_replace("%%FORM%%", $formoutput, $output);echo $output;exit();?>
trivia1.php: File that judge the user's answer.
<?phprequire("config.php"); if ($logged_in == 0) {	die('Sorry you are not logged in, this area is restricted to registered members. <a href="login.php">Click here</a> to log in.');}#$progressive determines whether the user is given another#random question after answering a question. If $progressive#is set to 0, the script will only display the results from#the previous question. If set to 1, it will display the#results along with another question. Because questions are#chosen in random order, it's possible that the same question#will appear twice in a row during a progressive game.$progressive = 1;$result="";$Points=1;#Judge the user's answer, if one was submittedif(isset($_POST["question"])) {	if($_POST["question"]) {		#Remove slashes that came through as submitted data		$question=stripslashes($_POST["question"]);		$idquestion=$_POST["idquestion"];		if($_POST["answer"]) {			#Find the if the answer submitted is the correct choice of the relevant question			$SqlA = "SELECT * from answer where answer.idq=$idquestion and answer.id=" . $_POST["answer"];			$regA=mysql_query($SqlA) or die(mysql_error());			$RowA = mysql_fetch_array($regA);			if ($RowA["correct"]==1) {				# update user stats and display if its a correct answer				$result="Correct!";			}			else {				$result="Incorrect!";				$Points=-1;			}		}		$update_points = "UPDATE registration SET points=points+$Points WHERE nickname = '".$_SESSION['nickname']."'";		mysql_query($update_points) or die(mysql_error());		#close the database connection, we just dont need anymore		mysql_close();		#Should we show another question?		if(!$progressive) exit();	}	else {		$result = "";	}}else {		$result = "";}$Url2Go="trivia.php?resultoutput=$result";Header("Location: $Url2Go");exit();?>
That's all the php code required, the following are the html templates files to run correctly the trivia timed test:

 

formtemplate.html: template file that include the script to control the time.

<html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>::Trivia::</title></head><body bgcolor="#99CCCC"><form name="form" method="POST" action="trivia1.php"><h3 align="center"><font color="#993300">Trivia!</font></h3><table width="90%" border="0" align="center" bgcolor="#000000" cellpadding="0" cellspacing="1">  <tr>	<td>	  <table width="100%" border="0" bgcolor="#FFFFFF">		<tr> 		  <td style="text-align:center;font-size:10pt;font-family:Verdana;font-weight:bold; text-decoration:underline">%%RESULT%%		  </td>		</tr>		<tr> 		  <td style="text-align:left;font-size:10pt;font-family:Verdana, Arial;">Question #%%NUMQUESTION%%: <span style="font-weight:bold;color:#FF0000;font-size:12pt">%%QUESTION%%</span>		  </td>		</tr>		<tr> 		  <td style="text-align:left;font-size:10pt;font-family:Verdana, Arial;">Which answer looks the best?		  </td>		</tr>		<tr> 		  <td style="text-align:left;font-size:10pt;font-family:Verdana, Arial;padding-left:20px">%%FORM%%		  </td>		</tr>		<tr>		<!-- countdown script --> 			<td style="text-align:left;font-size:10pt;font-family:Verdana, Arial;">Time Left: <input type="text" name="seconds" size="3">			<script language="javascript" type="text/javascript">				var myTime = 20;				function countDown() {					document.form.seconds.value = myTime;					if (myTime == 0) {						location.href="trivia1.php";					}					else if (myTime > 0) { 						myTime--;						setTimeout("countDown()",1000);					}				}								countDown();			</script>			</td>		</tr>		<tr> 		  <td style="text-align:center"><input type="submit" value="Answer" name="submit">		  </td>		</tr>	</table>	</td>  </tr></table></form><p align="center"><a href="logout.php"><font size="2" face="Verdana, Arial">Click here to Logout</font></a></p></body></html>
template4.html: Template file used in the login.php file if the user complete his number of tests per day.
<html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>::Trivia::</title></head><body bgcolor="#99CCCC"><h2 align="center"><font color="#FFFFFF">Trivia!</font></h2><table width="90%" border="0" align="center" bgcolor="#000000" cellpadding="0" cellspacing="1">  <tr>	<td>	  <table width="100%" border="0" bgcolor="#131313">		<tr> 		  <td>			<p><font size="2" face="Verdana, Arial">Sorry, but today you can not play our Trivia again, because you complete all your plays, please try again tomorrow.</p>			<p><font size="2" face="Verdana, Arial">Thanks to play our Trivia %%NICKNAME%%. <a href="logout.php"><font size="2" face="Verdana, Arial">Click here to Logout</font></a>.</p>		  </td>		</tr>	  </table>	</td>  </tr></table></body></html>
template5.html: Template file used in the trivia.php file if the user complete his number of tests per day.
<html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>::Trivia::</title></head><body bgcolor="#99CCCC"><h3 align="center"><font color="#993300">Trivia!</font></h3><table width="90%" border="0" align="center" bgcolor="#000000" cellpadding="0" cellspacing="1">  <tr>	<td>	  <table width="100%" border="0" bgcolor="#ffffff">		<tr> 		  <td> 			<p><font size="2" face="Verdana, Arial">Thanks to play our Trivia %%NICKNAME%%</p>			<p><font size="2" face="Verdana, Arial">Sorry, but today you can not play our Trivia again, because you complete all your plays, please try again tomorrow.</p>		  </td>		</tr>	  </table>	</td>  </tr></table><p align="center"><a href="logout.php"><font size="2" face="Verdana, Arial">Click here to Logout</font></a>.</p></body></html>
template3.html: Template file used in the trivia.php file if the user complete all the questions of the test.
<html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>::Trivia::</title></head><body bgcolor="#99CCCC"><h3 align="center"><font color="#993300">Trivia!</font></h3><table width="90%" border="0" align="center" bgcolor="#000000" cellpadding="0" cellspacing="1">  <tr>	<td>	  <table width="100%" border="0" bgcolor="#FFFFFF">		<tr> 		  <td> 			<p align="center"><font size="2" face="Verdana, Arial"><b><u>%%RESULT%%</u></b></font></p>			<p><font size="2" face="Verdana, Arial">Thanks to play our Trivia %%NICKNAME%%</p>			<p><font size="2" face="Verdana, Arial">You can play our Trivia %%PLAYSLEFT%% more time(s).</p>		  </td>		</tr>	  </table>	</td>  </tr></table><p align="center"><a href="logout.php"><font size="2" face="Verdana, Arial">Click here to Logout</font></a> or <a href="trivia.php"><font size="2" face="Verdana, Arial">Click here to Play again</font></a>.</p></body></html>
Well, as you can see there are a lot of improvements to do and i must do :( when i have some time in the near future i hope, so please feel free to PM me if you have any question.

 

Best regards,

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.