Countdown 10 min, run a .php file, then restart - php

My question is a simple yet I cannot find a way around it. I need a server time countdown script to run for 10 minutes, run a php file and when the countdown ends restart again.
I have read the jQuery scripts but all of them provide me with a countdown to a speciffic date then stop.
Can anyone point me to the right direction to find such a script?
This is what I have
<style style="text/css">
.lcdstyle{ /*Example CSS to create LCD countdown look*/
background-color:black;
color:lime;
font: bold 18px MS Sans Serif;
padding: 3px;
}
.lcdstyle sup{ /*Example CSS to create LCD countdown look*/
font-size: 80%
}
</style>
<script type="text/javascript">
function cdLocalTime(container, servermode, offsetMinutes, targetdate, debugmode){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
var servertimestring=(servermode=="server-php")? '<? print date("F d, Y H:i:s", time())?>' : (servermode=="server-ssi")? '<!--#config timefmt="%B %d, %Y %H:%M:%S"--><!--#echo var="DATE_LOCAL" -->' : '<%= Now() %>'
this.localtime=this.serverdate=new Date(servertimestring)
this.targetdate=new Date(targetdate)
this.debugmode=(typeof debugmode!="undefined")? 1 : 0
this.timesup=false
this.localtime.setTime(this.serverdate.getTime()+offsetMinutes*60*1000) //add user offset to server time
this.updateTime()
}
cdLocalTime.prototype.updateTime=function(){
var thisobj=this
this.localtime.setSeconds(this.localtime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}
cdLocalTime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}
cdLocalTime.prototype.showresults=function(){
var thisobj=this
var debugstring=(this.debugmode)? "<p style=\"background-color: #FCD6D6; color: black; padding: 5px\"><big>Debug Mode on!</big><br /><b>Current Local time:</b> "+this.localtime.toLocaleString()+"<br />Verify this is the correct current local time, in other words, time zone of count down date.<br /><br /><b>Target Time:</b> "+this.targetdate.toLocaleString()+"<br />Verify this is the date/time you wish to count down to (should be a future date).</p>" : ""
var timediff=(this.targetdate-this.localtime)/1000 //difference btw target date and current date, in seconds
if (timediff<0){ //if time is up
this.timesup=true
this.container.innerHTML=debugstring+this.formatresults()
return
}
var oneMinute=60 //minute unit in seconds
var oneHour=60*60 //hour unit in seconds
var oneDay=60*60*24 //day unit in seconds
var dayfield=Math.floor(timediff/oneDay)
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
hourfield=dayfield*24+hourfield
dayfield="n/a"
}
else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
minutefield=dayfield*24*60+hourfield*60+minutefield
dayfield=hourfield="n/a"
}
else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
var secondfield=timediff
dayfield=hourfield=minutefield="n/a"
}
this.container.innerHTML=debugstring+this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}
/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////
//Create your own custom format function to pass into cdLocalTime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left
//The values of these arguments may change depending on the "baseunit" parameter of cdLocalTime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc
//1) Display countdown using plain text
function formatresults(){
if (this.timesup==false){//if target date/time not yet met
var displaystring="<span style='background-color: #CFEAFE'>"+arguments[2]+" minutes "+arguments[3]+" seconds</span> left until launch time"
}
else{ //else if target date/time met
var displaystring="Launch time!"
}
return displaystring
}
//2) Display countdown with a stylish LCD look, and display an alert on target date/time
function formatresults2(){
if (this.timesup==false){ //if target date/time not yet met
var displaystring="<span class='lcdstyle'>"+arguments[2]+" <sup>minutes</sup> "+arguments[3]+" <sup>seconds</sup></span> left until launch time"
}
else{ //else if target date/time met
var displaystring="" //Don't display any text
alert("Launch time!") //Instead, perform a custom alert
}
return displaystring
}
</script>
<div id="cdcontainer"></div>
<script type="text/javascript">
//cdLocalTime("ID_of_DIV_container", "server_mode", LocaltimeoffsetMinutes, "target_date", "opt_debug_mode")
//cdLocalTime.displaycountdown("base_unit", formatfunction_reference)
//Note: "launchdate" should be an arbitrary but unique variable for each instance of a countdown on your page:
var launchdate=new cdLocalTime("cdcontainer", "server-php", 0, "April 28, 5012 00:05:00", "debugmode")
launchdate.displaycountdown("days", formatresults2)
</script>
Any ideas?

It seems like what you want is a cron job; which can execute a script at predefined times or intervals. Setting up a cron depends a little bit on the server environment in which you are executing it.
To update using a countdown script in JavaScript:
var count = 600;
function hitPhpScript() {
var xhr = new XMLHttpRequest();
xhr.open("get", "myscript.php", true);
xhr.send(null);
startCountdown();
}
function startCountdown() {
count = 600;
doCountdown();
}
function doCountdown() {
count--;
if (count > 0) {
document.getElementById("countdown_label").innerHTML = count + " seconds left";
setTimeout("doCountdown()", 1000);
} else {
hitPhpScript();
}
}

This is the chunk that initializes the clock to 30 minutes on page load:
$date = date('i');
$sec = date('s');
$diff = ($date < 30) ? 1800 - (($date * 60) + $sec) : 3600 - (($date * 60) + $sec); //set diff to run split on the half hour.
$hld_diff = $diff;
What's happening here is
$date = date('i') //is taking the minutes portion of the current time
$sec = date('s') //is taking the seconds portion of the current time
The next line is saying if the number of minutes is less than 30, set $diff to 1800 seconds (i.e. 30 minutes) minus the current time minutes and seconds. In other words - set the $diff value to the number of seconds until the current time will hit 00 mins 00 secs. If the number of minutes is greater than or equal to 30, do a similar thing but setting $diff to the number of minutes and seconds until the current time minutes and seconds reaches 30 and 0 respectively.
So if you want to use this same code but want to set it to 10 minutes, first you have to decide what number of minutes on the clock you want the countdown to end. To keep it simple we'll say it will end on 0, 10, 20, 30, 40, and 50.
Therefore you could do something like this:
if($date < 10)
$diff = 600 - (($date * 60) + $sec);
else if($date < 20)
$diff = 1200 - (($date * 60) + $sec);
else if($date < 30)
$diff = 1800 - (($date * 60) + $sec);
else if($date < 40)
$diff = 2400 - (($date * 60) + $sec);
else if($date < 50)
$diff = 3000 - (($date * 60) + $sec);
else
$diff = 3600 - (($date * 60) + $sec);
That should be all you need (unless I've overlooked something)

its a countdown for a game, i need a visual countdown to when the cash or whatever is gonna be added.
You wouldn't usually script this using an "actual" countdown. The logic is simple enough to program in an "non-realtime" fashion. The next time the user logs on/refreshes the page/does something, you can run all the calculations that are necessary to provide the user with as much money as he should have received since the last time he looked at the page. You do not actually have to give the user the money exactly after 10 mins.
For such games, you'd usually have a cron job/daemon running every minute or so that recalculates all amounts of all users in this way. The visual countdown is just a gimmick on the client-side.

Related

How should I prepare the database of the counter counting down in seconds with php?

I'm trying to set up counter logic for a game. The critical point here is that every user who enters this page sees the same second at that moment. I will have a counter that counts down from 25 and everyone will place their bets during this time. When the 25 seconds are over, a 10 second counter will start, during which 10 seconds the winning bet will be announced. How can I set up the database setup so that these counters are repeated continuously?
I am using the following code for javascript, but every time I enter the page it starts from 25
var interval = 25000;
var interval1 = 10000;
var endTime;
function millisToMinutesAndSeconds(millis) {
// Use floor instead of toFixed
var seconds = Math.floor((millis % 60000) / 1000);
return (seconds < 10 ? "0" : "") + seconds;
}
function reset() {
// Use Date.now() instead of +new Date()
// And create a cycle length that covers both intervals
endTime = Date.now() + interval + interval1;
}
reset();
setInterval(function () {
var remaining = endTime - Date.now();
if (remaining >= 0) {
// Adjust the time to display
// depending on where in the total interval we are:
if (remaining >= interval1) remaining -= interval1;
document.getElementById("timer").innerText =
millisToMinutesAndSeconds(remaining);
} else {
reset()
}
}, 100);
You just need to put the end date and time in database. The countdown must be done with javascript.
Get the date from backend (database) with php and pass it to javascript. Then do the countdown with js.
This tutorial seems exactly like what you need.

How to get first time from server by php and put in JavaScript

How can I get first time from server by php?
I've tested this code but it does not work. It gets the time but it is not counting? What's the problem?
<script type="text/javascript">
function GetClock(){
d = new Date(<?php echo date("y, n, j, G, i, s");?>);
nhour = d.getHours();
nmin = d.getMinutes();
nsec = d.getSeconds();
if(nhour == 0) {
ap = " AM";nhour = 12;
} else if(nhour <= 11) {
ap = " AM";
} else if(nhour == 12) {
ap = " PM";
} else if(nhour >= 13) {
ap = " PM";nhour -= 12;
}
if(nmin <= 9) {
nmin = "0" +nmin;
} if(nsec <= 9) {
nsec = "0" +nsec;
}
document.getElementById('clockbox').innerHTML=""+nhour+":"+nmin+":"+nsec+ap+"";
setTimeout("GetClock()", 1000);
}
window.onload=GetClock;
</script>
Explanation
The question is why are you using PHP to write a datetime into the Date object in JS?
The PHP will only write out the time at the point at which the page renders, it will never change again.
You are then setting your counter based on a Javascript setTimeout every 1 second, expecting the clock to increment in seconds, but it is always based on the same original time (the page render time) and is always incremented by 1 second.
For example. The page loads at 12:00:00 on June 3 2013. Your code looks like this:
d = new Date(13, 6, 3, 12, 0, 0);
at the time the pages loads (if you view source)
1 second later the setTimeout fires and renders the clock at 12:0:01, based on the starting time in the date object.
But your starting time never changes, so each further second that passes and triggers setTimeout will base the calculations on 12:00:00 not the current time
TLDR; and answer
Remove the PHP!
d = new Date();
Alternatively, if you absolutely have to use server time. You would need to initialise the date object as you have done, but then store a count of how many seconds have passed and calculate the difference

Compare PHP server time with JavaScript time (client browser time)

I am making a notification system which require the time since functionality.
I am using this script for timesince function(jQuery):
$.fn.updateSince = function(interval) {
var times = this.map(function(){ return { e: $(this), t: parseInt($(this).html()) }; });
var format = function(t) {
if(t > 86400) {
return Math.floor(t / 86400) + ' days ago';
} else if (t > 3600) {
return Math.floor(t / 3600) + ' hours ago';
} else if (t > 60) {
return Math.floor(t / 60) + ' minute ago';
} else if (t > 50) {
return '50 seconds ago';
} else if (t > 40) {
return '40 seconds ago';
} else if (t > 30) {
return '30 seconds ago';
} else if (t > 25) {
return '25 seconds ago';
} else if (t > 15) {
return '15 seconds ago';
} else if (t > 10) {
return '10 seconds ago';
} else {
return 'a few seconds ago';
}
}
var update = function(){
var now = new Date().getTime();
$.each(times, function(i, o){
o.e.html(format(Math.round((now - o.t) / 1000)));
});
};
window.setInterval(update, interval);
update();
return this;
}
The notifications are stored in MySQL database , each notification has a timestamp on it that is in this format: 2012-12-26 06:21:28
I use PHP strtotime and change it into UTC format when obtaining the time out of the database for each notificaiton item:(php)
$rows['time']= strtotime($temp_time." UTC");
When I pass it back to the client browser , using ajax. I will multiply the UTC time(from database) with 1000(javascript)
var time = parseInt(dbtime * 1000);
Then I can use the jQuery timesince function to turn it into time ago.
Problem:
My server time varies with client browser time.
How do I make them "compatible" with each other.
For example , a notification is made 2 hours ago according to client browser.
But PHP says its made 7 hours ago.
because client browser timezone is different with my server's
My logic is:
1. [PHP] Get current time , and use the notification time obtained from database to subtract with it.
database time - current time = time difference on server end
[PHP] Then we get a time difference. in this case 7 hours.
[PHP] How do i turn 7 hours into UTC format?
[Javascript] Send the current client browser time , also in UTC format to php script.
[PHP] client browser time - 7 hours(UTC?) = actual time of notification created for javascript use.
[PHP] Send back the results to Javascript , so now the time can be 2 hours ago on client browser's end.
How do I do this?
Just for info , UTC format is like(multiplied with 1000) : 1314952284779
Your logic could be:
Convert the notification time to UNIX timestamp using strtotime (or any similar function)
Use JavaScript Date function with this value (multiplied by 1000) to re-build the date
Use (new Date) - thatDate to calculate the difference
Convert to hours, minutes and seconds
The problem I see here is in the first step. You mention that the dates are stored as 2012-12-26 06:21:28 but what timezone does this date correspond to? If it is the same time as the server timezone then using strtotime("2012-12-26 06:21:28") is sufficient to generate correct timestamp.
i had the same problem to i store the ip of the user in the db and then convert that to location and get the timezone then uses this functionality. main reason of doing that is that i future you might me considering to get info about your user so that approach also gonna help then. You can use interval triggered function to run the code
j(document).ready(function () {
window.initial = 0;
window.setInterval(timeincrement, 60000);
function timeincrement() {
initial = initial + 60;
j('.coment').each(function () {
var timefromserver = j(this).find('input[type=hidden]').val();
timefromserver = parseInt(timefromserver);
if ((timefromserver / 216000) < 1) {
var secgone = timefromserver + initial;
var timeelasped = secgone / 60;
if (Math.floor(timeelasped) < 1) {
j(this).find('.lightgrey').text("Few seconds ago");
} else if (Math.floor(timeelasped) < 60) {
var innertext = timeelasped + " minutes ago";
j(this).find('.lightgrey').text(innertext);
} else if (Math.floor(timeelasped / 60) > 0) {
var hourgone = Math.floor(timeelasped / 60);
var innertext = hourgone + " hours ago";
j(this).find('.fdlightgrey').text(innertext);
}
}
});
}
});
For your info new Date().getTime() in JavaScript return UTC time, as far as the client clocks are right this means that you don't have to deal with different time zones of users, all you have to do is to provide the times from your server in UTC.
In PHP you should either use the gmdate function to create UTC time strings or simply don't format it and just ship the raw UNIX UTC time that you get from the time function.
In short UTC everywhere, then it works. As a bonus it works like daylight savings didn't exist.
You could also also do an adjustment to account for incorrect times on the client by sending a "now" time stamp when the page is first loaded, calculate how long ago that is on the client, and subtract this result from all future calculations. But given that practically all computers automatically adjust their clock to that of a time server it is quite rare that a computer clock is off by more than a few seconds.
if mysql data is UTC, i use Date.getTimezoneOffset() in JavaScript and apply it (offset is in minutes: -120 = GMT+2) to the time stored in mysql (obtained via php) when displaying historical time (when event happened) for a user.
RAMBLINGS:
also serves to compare current time with mysql data (never trust a user's clock, but their timezone is usually correct [except for frequent-flyers' laptops, ouch]).
i take care to tell the user what her timezone difference is (either by publishing GMT +/- XX or something like "HH:MM this should be your local time, please fix clock if it isnt") and asking them to confirm it, if necessary. your code will deal with the situation according to your relationship with user ("fix that clock, darnit" or "yes, hmmmm, would you like us to fix our clocks to fit paris time [though we are in argentina], madame?")

countdown php jquery post ajax

I'm designing a website where there is a little game going on. Each user that participates has 99 minutes to complete it otherwise we display a game over state. Here is what I managed to do so far using jQuery post.
I've been able to display the timer. In the PHP I've set the target time to 99*60 seconds but I cant set the starting time to 0 as I'll do the difference beteen those to values for the countdown.
Furthermore, as each user is able to quit the page I want to be able to store the time when they left. All I am able to do is store the countdown value, let's say 5845, in the DB when they log off. Though I tried updating the table with each call to the jQuery post, it just makes it worse.
Here is my jQuery:
function countdown() {
var i = (new Date().getTime() / 1000) + (99 * 60);
setTimeout(function () {
$.post(\'countdown.php\',{target:i},function(data){
$('#countdown').html(data);
});
countdown();
},1000);
}
countdown();
Here is the PHP:
if (!empty($resm['Countdown']) || $resm['Countdown'] >= 0) {
$target = (99 * 60);
$countdown = ($target - $current);
$_SESSION['currenttime'] = $countdown;
$hours = floor($countdown / 3600);
$min = floor($countdown / 60);
$r_min = floor(($countdown - ($hours * 3600)) / 60);
$sec = floor($countdown - ($min * 60));
if ($min == 0) {
echo $target.' '.$current.' '.$countdown;
echo '<br/>'.$min.' minutes '.$sec.' seconds left';
} else {
echo 'Time Over';
$sql = "UPDATE bs10000099 SET Upgradedlevel='2',Activated='2',Countdown='5940' WHERE MemberID='$memberid'";
mysql_query($sql);
}
}
I cant figure out how to set the starting time or how to prevent countdown() restart on refresh page.
I'm not sure what kind of security you want, but getting time from Javascript is not really secure since JS gets the time from the computer instead of the server.
With your example, I would be able to play the game, wait until there's 10 minute left, and just roll back time on my desktop and it will reset. Or roll back a year and have 100000 minutes left!
I suggest you use server time.
Here is what I would do:
When the test starts, get the UNIX time + 90 minutes. This will give you the final time.
PHP
if (!isset($_SESSION['end'])) {
$_SESSION['end'] = strtotime("+90 minutes");
}
$remaining = $_SESSION['end'] - time();
if ($remaining > 0) {
echo json_encode(array(
"remaining" => $remaining
));
} else {
// finished! write code here.
}
You can then do a simple $.getJSON() to get the remaining seconds and display it.
Since you kept the "end" time, even if the users leave, the timer will continue.

Best way to implement a timer in Javascript and php

I am developing a quiz application in php and Javascript. The quiz starts when the user hits a submit button(I don't control when the quiz should start). The quiz should stop after a specific time (I decide that).
I don't want to rely completely on the client computer to stop the time since the client pc time can be altered.
The quiz should not restart on page refresh.
I know setInterval and basic javascript. The function I have developed so far works perfectly, but the quiz restarts on page refresh.
function formatSecondsAsTime(secs) {
var hours = Math.floor(secs / 3600);
var minutes = Math.floor(secs / 60) - (hours * 60);
var seconds = secs - (hours * 3600) - (minutes * 60);
return hours + ':' + minutes + ':' + seconds;
}
function startTimer(mytime) {
mytime = mytime.split(":");
hrs = mytime[0];
parseInt(hrs, 10);
mins = mytime[1];
parseInt(mins, 10)
secs = mytime[2];
parseInt(secs, 10);
if (hrs > 0 || mins > 0 || secs > 0) {
timerVar = setInterval(function () {
if (secs > 0) //time is less than a minute
{
displayTime(hrs, mins, secs--);
}
else if (secs == 0 && mins > 0) {
displayTime(hrs, mins = mins - 1, secs = secs + 59);
}
else if (secs == 0 && mins == 0 && hrs > 0) {
displayTime(hrs--, mins = mins + 59, secs = secs + 59);
}
else if (secs == 0 && mins == 0 && hrs == 0) {
clearTimeout(timerVar);
displayTime(0, 0, 0);
}
}, 1000);
}
else {
displayTime(0, 0, 0);
}
}
function displayTime(hrs, mins, secs) {
if (secs > 0 || hrs > 0 || mins > 0) {
if ((secs.toString()).length < 2) secs = "0" + secs;
if ((mins.toString()).length < 2) mins = "0" + mins;
if ((hrs.toString()).length < 2) hrs = "0" + hrs;
document.getElementById("quiztime").innerHTML = "Time remaining: " + hrs + ":" + mins + ":" + secs;
}
else {
document.getElementById("quiztime").innerHTML = "Quiz has ended!";
alert("Quiz has ended. Click ok to continue.");
document.forms["answerForm"].submit();
}
}
Please suggest me the best way to do it.
Thank you.
One of the best ways to achieve this is the following: on the begin of the quiz, send an AJAX request to the server telling your PHP script that it's started. Your PHP script should store a session variable for that user holding the start time. On submit of the quiz, check to make sure that the difference between the current time and the session stored start time is no greater than your allowed amount of time.
Session variables can't be edited or viewed by the client. If the client loads the page in the middle of the quiz, set the JS timer amount to whatever time is left based on the start time in the session.
I'll suggest you to use cookies to determine if the current user is in some started quiz. I.e. when the user clicks submit you are setting a cookie with PHP and record the started time in a database. Every time when the user visits the page you will check for that cookie and will fetch the record from the database. That's how you will find out how much time is left till the end of the quiz.
Cookies are the key to remembering the start time. Set the start time in a cookie, in php on submit. This same time should be written to the page in a script element (then both the server and client will know the start time). To protect the cookie you can encrypt it server-side. You can verify that the start time has not been tampered with by comparing the value in the cookie with the one in js (when the test completes).
If the page reloads and the cookie exists, pull the time from the cookie rather than setting new time.

Categories