how to make countdown timer to not reset on page refresh - php

I am creating an online exam page for my project. I have a countdown timer, but it resets on page refresh. How can I make it not to reset?
The timer is set by fetching time from db. I am using php mysql. Please help me.
Here is my code.
<?php
$result=mysql_query("select * from test where testid='29'");
while($time=mysql_fetch_array($result)){
$dateFormat = "d F Y -- g:i a";
$targetDate = time() + ($time['duration']*60);
$actualDate = time();
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown ()
{
seconds--;
if (seconds < 0){
minutes--;
seconds = 59
}
if (minutes < 0){
hours--;
minutes = 59
}
if (hours < 0){
hours = 23
}
document.getElementById("remain").innerHTML = " "+hours+" hr "+minutes+" min "+seconds+" sec";
SD=window.setTimeout( "setCountDown()", 1000 );
if (minutes == '00' && seconds == '00') {
seconds = "00"; window.clearTimeout(SD);
window.location = "result.php"
}
}
</script>
</head>
<body onLoad="setCountDown();">
<div id="remain">
<?php echo "$remainingHour hours, $remainingMinutes minutes, $remainingSeconds seconds";?>
</div>

You should read the value into session variable and using that afterwards:
<?php
session_start();
if (isset($_SESSION['targetdate'])) {
// session variable_exists, use that
$targetDate = $_SESSION['targetdate'];
} else {
// No session variable, red from mysql
$result=mysql_query("select * from test where testid='29' LIMIT 1");
$time=mysql_fetch_array($result);
$dateFormat = "d F Y -- g:i a";
$targetDate = time() + ($time['duration']*60);
$_SESSION['targetdate'] = $targetDate;
}
$actualDate = time();
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)- ($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)- ($remainingHour*60*60))-($remainingMinutes*60));
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
?>

When the user starts the exam, save the start time in the database. Use that for everything. Don't rely on client side code for this as the user can easily modify it.
If you save the start time, you know when the user started and what the current time is. You can use that to see if time is up or not. A javascript timer is good to show how much time is remaining, but it should be getting that info from the database.

You'll probably need to register a table like active_exams with an examId field and datetimeStarted. Then load the timer as the number of seconds for that exam since it was started.
You may be able to create some workaround with cookies, localStorage or even the session but keep in mind those will be modifiable (or at least forgettable in the case of the session) by the user.

Page refresh doesn't matter if you have the Timer's "start-time" saved in your database for particular user.
Fetch this "start-time" from database and compute it to get the consumed time and accordingly show the remaining or elapsed time.

Related

How to make a countup timer instead of a countdown timer? (PHP, JQUERY AJAX)

I made a countdowntimer in PHP and jQuery AJAX who is showing every second the variable named $timeleft.
timer.js
$(function()
{
var timertext = $("[timer]");
setInterval(function()
{
$.post("timer.php", {type : "timerupdate"}, function(data)
{
timertext.html("Time left: " + data + " seconds")
});
}, 1000);
});
timer.php
date_default_timezone_set("Europe/Amsterdam");
$timecountdownend = strtotime("2020-05-18 14:30:00");
$timecountdownstart = strtotime("now");
$startdatetime = "2020-05-18 14:07:00"; //variable for starting datetime
if(date('Y-m-d H:i:s') >= $startdatetime){
$timeleft = $timecountdownend - $timecountdownstart;
if(isset($_POST["type"]) === true && $_POST["type"] == "timerupdate")
{
echo ($timeleft);
}
}
Explained: a timer that starts when it's a specific time ($startdatetime) and counting the seconds till the $timecountdownend time. It's working fine, but I actually want to count up the second instead of counting down. So that it start counting with 1 second if $startdatetime has reached and every second is counting up till the $timecountdownend has reached. How can I do this with strtotime? I've tried many things like $timeleft = $timecountdownend - strtotime(date('Y-m-d H:i:s')); but it didn't work.
Many thanks in advance.
First if You have timeleft its Your counter : -2820
You can simply multiple it by (-1) : -2820 * (-1) = 2820
date_default_timezone_set("Europe/Amsterdam");
$timecountdownend = strtotime("2020-05-18 14:30:00");
$timecountdownstart = strtotime("now");
$startdatetime = "2020-05-18 14:07:00"; //variable for starting datetime
$timeleft = $timecountdownend - $timecountdownstart;
echo ($timeleft);
echo(PHP_EOL);
echo ($timeleft*(-1));
echo(PHP_EOL);
echo( date('Y-m-d h:i:sa',strtotime($startdatetime)+$timeleft*(-1)));
http://sandbox.onlinephpfunctions.com/code/792ec42255d85a45c377b6e8d34cbde143430824

countdown timer using php, can't make it work

i am making a php countdown timer that display only minutes and seconds.
here is my code:
$time = "10:00";
$time_min = substr($time, 0,2);
echo $time_sec = substr($time, 3) . "<br>";
$current = date("i:s");
$target = date("i:s" , mktime(0,$time_min,0,0,0,0));
echo $current-$target . "<br>";
echo $target;
the output should be the remaining time from the time the user opens the page.
Not knowing the details of your jQuery I am taking a shot at this.
I prefer working in seconds, so to get the $timeRemaining (you must know the initial time to do this) at any given instant in the 10 minute window, I would do this:
$targetTime = time() + 600; //you have to save this either in database or as variable somewhere
Then on subsequent opening of relevant php file the following code could be used if targetTime is saved in database
$sqlTime = mysqli_fetch_assoc(mysqli_query($cxn, "SELECT targetTime FROM timeTable WHERE id = '$myID'"));
$currentTime = time();
$timeRemaining = (($sqlTime['targetTime'] - $currentTime) / 60) . ":" . (($sqlTime['targetTime'] - $currentTime) % 60);

PHP/Javascript countdown script

Note * I want some one to fix it and tell me how they did it not tips on how to do it or coments about php nd java mixed in it *
I have a countdown script that is working, but when it hits the target date the timer keeps on going to a negative time. I want it to stop on that target date and just display a finishing message. It's live on my site. I just need help editing the countdown script.
I want to keep the same layout. I need some help adding the finishing message and stopping it from going into the negative date, or just make it not display the 0days, 0 hours, 0mins, 0sec until the site's officially released. When that finally happens, I want it to display a message.
countdown script
<?php date_default_timezone_set('EST'); ?>
<?php
// Define your target date here
$targetYear = 2011;
$targetMonth = 9;
$targetDay = 1;
$targetHour = 20;
$targetMinute= 00;
$targetSecond= 00;
// End target date definition
// Define date format
$dateFormat = "Y-m-d H:i:s";
$targetDate = mktime($targetHour,$targetMinute,$targetSecond,$targetMonth,$targetDay,$targetYear);
$actualDate = time();
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$targetDateDisplay = date($dateFormat,$targetDate);
$actualDateDisplay = date($dateFormat,$actualDate);
?>
<script type="text/javascript">
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
</script>
<body onLoad="setCountDown();">
<center><?php echo "$remainingDay days, $remainingHour hours, $remainingMinutes minutes and $remainingSeconds seconds";?> untill official release</center>
how its added on the site
<script type="text/javascript">
$(function() {
/* Union War */
$("#Countdown2").load("http://imperialism.zxq.net/includes/process/uwcountdown.php");
setInterval(function(){
$("#Countdown2").load("http://imperialism.zxq.net/includes/process/uwcountdown.php");
}, 1000);
});
</script>
<div id="uwCD" class="uwCD">
<div id="Countdown2"></div>
</div>
I recommend this jQuery countdown plugin; just pass the PHP value to the jQuery plugin call.
if($targetDate != $actualDate && $targetDate > $actualDate) {
echo "$remainingDay days, $remainingHour hours, $remainingMinutes minutes and $remainingSeconds seconds";
} else {
echo "0 days, 0 hours, 0 minutes and 0 seconds";
}
try using this http://www.timeanddate.com/counters/customcount.html everything is done for you and its worked fine and if anything you can just edit the look of the skin to fit your website
if($targetDate != $actualDate && $targetDate > $actualDate) {
echo "$remainingDay days, $remainingHour hours, $remainingMinutes minutes and $remainingSeconds seconds";
} else {
echo "0 days, 0 hours, 0 minutes and 0 seconds";
}

How to make a countdown using PHP

Im creating a website for my brothers wedding. And so far all is going well. However, he wants a countdown to the wedding on the homepage;
Time left until the wedding: X months, X days, X hours.
I would preferebly like to do this using php, but would be open to other suggestions.
if you can help me with ideas for the coding, or just point me to relevant material, that would be useful.
The wedding is on Saturday 30th July.
If your need your counter to be displayed only on page refresh and be static once the page is loaded, then PHP will be fine.
If you need the countdown to get refreshed when the page is displayed, you'll need to use JavaScript.
Personally I would go for something already implemented, like that small script.
Following is the code snippet I have copied from the W3Schools website, while added my PHP code to get the "countdown to" timestamp and the "now" timestamp.
You will see I have commented out the original JavaScript code and replaced it with PHP code in two places, so it's clear to tell what's the difference between two options.
Basically when you think the "server time" is more reliable in your case, you can adopt the PHP approach.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
// Set the date we're counting down to
// 1. JavaScript
// var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();
// 2. PHP
var countDownDate = <?php echo strtotime('Sep 5, 2018 15:37:25') ?> * 1000;
var now = <?php echo time() ?> * 1000;
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
// 1. JavaScript
// var now = new Date().getTime();
// 2. PHP
now = now + 1000;
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " +
minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
</body>
</html>
For Static Countdown :
<?php
//A: RECORDS TODAY'S Date And Time
$today = time();
//B: RECORDS Date And Time OF YOUR EVENT
$event = mktime(0,0,0,12,25,2006);
//C: COMPUTES THE DAYS UNTIL THE EVENT.
$countdown = round(($event - $today)/86400);
//D: DISPLAYS COUNTDOWN UNTIL EVENT
echo "$countdown days until Christmas";
?>
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / 60*60*24);
$hours = floor(($secondsLeft - $days*60*60*24) / 60*60);
echo "$days days and $hours hours left";
Code top by user Neil E. Pearson didnĀ“t work, he forgot to write there the brackets (), working solution is:
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / (60*60*24)); // here the brackets
$hours = floor(($secondsLeft - ($days*60*60*24)) / (60*60)); // and here too
echo "$days days and $hours hours left";
$Target_Date = 1699458858; //expire data
$Time_Left = $Target_Date - time();
$days = floor($Time_Left / (60*60*24));//day
$Time_Left %= (60 * 60 * 24);
$hours = floor($Time_Left / (60 * 60));//hour
$Time_Left %= (60 * 60);
$min = floor($Time_Left / 60);//min
$Time_Left %= 60;
$sec = $Time_Left;//sec
echo "$days days and $hours hours and $min min and $sec sec left";
I would not use php (serverside) for this. Because you need to refresh your page every time to see the counting. Preferably use javascript (clientside) for this, more specific jquery (javascript framework). And look for a jquery plugin such as: http://keith-wood.name/countdown.html
If you want something realtime, you'll need to use client-side scripting, namely JavaScript.
You can do it in PHP, but it won't "animate":
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / 60*60*24);
$hours = floor(($secondsLeft - $days*60*60*24) / 60*60);
echo "$days days and $hours hours left";
You could put some more math in for months, but it gets fuzzier because a month isn't a fixed amount of time.
The other way would be to use the date() function to pick out the individual elements (hour, minute, second, day, month etc) and use rollover math, but it's a lot of bother for a 'nice effect'.
Let me know if you want a JavaScript example. Don't bother with jQuery - it's a canon for killing a mosquito :)
try this
<?php
$target = mktime(0, 0, 0, 9, 25, 2011) ;//set marriage date
$today = time () ;
$difference =($target-$today) ;
$month =date('m',$difference) ;
$days =date('d',$difference) ;
$hours =date('h',$difference) ;
print $month." month".$days." days".$hours."hours left";
?>
Try this
$wedding = strtotime("2014-02-20 12:00:00"); // or whenever the wedding is
$current=strtotime('now');
$diffference =$wedding-$current;
$days=floor($diffference / (60*60*24));
echo "$days days left";
Try this static countdown.
<?php
//Current Date And Time
$todaytime = time();
//Set Date And Time OF The Event
$eventdate = mktime(0,0,0,0,28,2021);
//Calculate Days Until The Event
$countdown = round(($eventdate - $todaytime)/86400);
//Display Countdown
echo "$countdown days until the event";
?>

Countdown Timer

My project in php
I want to create a countdown timer for asking question in limited timeframe like LMS
here i have use the javascript countdown timer but when refresh the page javascript timer are reset.
You could store the start time in a php session. Then everytime you load a page you can continue the countdown timer with javascript, e.g.
<?php
//on every page
session_start();
//when you start
$_SESSION['start_time'] = time();
Then on every page:
<script type="text/javascript">
var startTime = <?php echo $_SESSION['start_time']; ?>;
//calculate remaining time
</script>
You will need to watch for when the timezones are different, or when the client's clock is wrong. Maybe instead you could calculate the remaining time in seconds and print that into javascript on each page, but then you could have innacuracy over high latency connections etc.
Try something like:
<?php
session_start();
//to reset the saved countdown
if (!empty($_REQUEST['resetCountdown']))
{
unset($_SESSION['startTime']);
}
if (empty($_SESSION['startTime']))
{
$_SESSION['startTime'] = time();
}
//In seconds
$startTime = time() - $_SESSION['startTime'];
?>
<script type="text/javascript">
var countdown = 60; //in seconds
var startTime = <?php echo $startTime; ?>;
startCountdown(startTime, countdown);
function startCountdown(startFrom, duration)
{
//countdown implementation
}
</script>
You could also store the timer in a session variable in PHP so that when the page is refreshed the time is still preserved.
try this
<script>
// Set the date we're counting down to
var countDownDate = new Date("Aug 1, 2017 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
and also put this under body tag.
<p id="demo"></p>

Categories