Таймер для онлайн-экзаменационной системы для хранения времени для каждого отдельного раздела - PullRequest
1 голос
/ 11 января 2012

Я разрабатываю онлайн-экзамен, для которого мне нужно иметь таймер обратного отсчета / часы, которые будут отображаться в течение всей продолжительности теста.Кроме того, при отображении окончательного результата также должно отображаться время, затрачиваемое на решение каждого отдельного вопроса, а также общее время, затрачиваемое на тестирование.

Каковы возможные наилучшие подходы для реализации этой функции ??

<?php

$countfile = "counter.txt";

// location of site statistics.
$statsfile = "stats.txt";

// checks whether the file exist, if not then server will create it.
if (file_exists($countfile)) {

// open the counter hit file.
$fp = fopen($countfile, "r"); 

// reads the counter hit file and gets the size of the file.
$output = fread($fp, filesize($countfile));

// close the counter hit file.
fclose($fp); 

// get the integer value of the variable.
$count = intval($output);
}

// if file is doesn't exist, the server will create the counter hit file and gives a value of zero.
else { 
$count = 0;
}

// showcount function starts here.
function ShowCount() { 

// declares the global variables.
global $ShowCount, $countfile, $statsfile, $count;

// get the current month.
$month = date('m');

// get the current day.
$day = date('d');

// get the current year.
$year = date('Y');

// get the current hour.
$hour = date('G');

// get the current minute.
$minute = date('i');

// get the current second.
$second = date('s');

// this is the date used in the stats file
$date = "$month/$day/$year $hour:$minute:$second";

// this is the remote IP address of the user.
$remoteip = getenv("REMOTE_ADDR");

// some of the browser details of the user.
$otherinfo = getenv("HTTP_USER_AGENT");

// retrieve the last URL where the user visited before visiting the current file.
$ref = getenv("HTTP_REFERER");

// open the statistics file. 
$fp = fopen($statsfile, "a");

// put the given data into the statistics file.
fputs($fp, "Remote Address: $remoteip | ");
fputs($fp, "Information: $otherinfo | ");
fputs($fp, "Date: $date | ");
fputs($fp, "Referer: $ref\n");

// close the statistics file.
fclose($fp);

// adds 1 count to the counter hit file.
$count++;

// open the counter hit file.
$fp = fopen($countfile, "w");

// write at the counter hit file.
// if the value is 34, it will be changed to 35.
fwrite($fp, $count);

// close the counter hit file.
fclose($fp);

// showcount variable is equal to count variable.
$ShowCount = $count;

// return the value of the count variable into showcount variable.
return $ShowCount;
}

// display the value in the counter hits file.
echo showcount(), " visits";

?> 

Я использую этот сценарий для отслеживания статистики посещений и времени посещения ... он работает нормально. Однако я не могу отследить время отдельного вопроса в каждой категории экзамена (каждый экзамен имеет несколькокатегории, имеющие несколько вопросов).Нужна помощь

Ответы [ 2 ]

2 голосов
/ 11 января 2012

Используя сеанс, вам нужно отслеживать, когда истекает время пользователя для раздела

<?php
// Upon starting the section
session_start();
$_SESSION['TIMER'] = time() + 600; // Give the user Ten minutes
?>

Не делайте этого при перезагрузке страницы, потому что они могут просто обновить страницу и сбросить таймер

На странице используйте Javascript для отображения часов:

<script type="text/javascript">
var TimeLimit = new Date('<?php echo date('r', $_SESSION['TIMER']) ?>');
</script>

Затем вы можете использовать переменную TimeLimit для отображения обратного отсчета

<script type="text/javascript">
function countdownto() {
  var date = Math.round((TimeLimit-new Date())/1000);
  var hours = Math.floor(date/3600);
  date = date - (hours*3600);
  var mins = Math.floor(date/60);
  date = date - (mins*60);
  var secs = date;
  if (hours<10) hours = '0'+hours;
  if (mins<10) mins = '0'+mins;
  if (secs<10) secs = '0'+secs;
  document.body.innerHTML = hours+':'+mins+':'+secs;
  setTimeout("countdownto()",1000);
  }

countdownto();
</script>
0 голосов
/ 11 января 2012

Вы можете достичь этого, выполнив

  1. Когда студент начинает экзамен, сохраните StartTime в каком-нибудь магазине / базе данных.
  2. Для отображения обратного отсчета вы можете использовать JavaScript на стороне клиента. Напишите функцию, которая займет 2 раза, сначала будет время сервера, а второй будет StartTime. Используя их, вы можете узнать сколько времени кандидат решает задачу , и из этого вы можете узнать оставшееся время . Используя setInterval JavaScript, вы можете показать тикающие часы.
  3. В течение времени, затрачиваемого на решение вопроса, запишите время, в течение которого вопрос виден кандидату.
  4. Добавьте время, затраченное на отдельный вопрос, и укажите общее время.

Полагаю, это тот ответ, который вы искали.

...