Pergunta

I need to make a page that has a timer counting down. I want the timer to be server side, meaning that when ever a user opens the page the counter will always be at the same time for all users. When the timer hits zero I need to be able to run another script, that does some stuff along with resetting the timer.

How would I be able to make something like this with php?

Foi útil?

Solução

Judging from "when ever a user opens the page" there should not be an auto-update mechanism of the page? If this is not what you meant, look into AJAX (as mentioned in the comments) or more simply the HTML META refresh. Alternatively, use PHP and the header()

http://de2.php.net/manual/en/function.header.php

method, described also here:

Refresh a page using PHP

For the counter itself, you would need to save the end date (e.g. a database or a file) and then compare the current timestamp with the saved value.

Lets assume there is a file in the folder of your script containing a unix timestamp, you could do the following:

<?php
$timer = 60*5; // seconds
$timestamp_file = 'end_timestamp.txt';
if(!file_exists($timestamp_file))
{
  file_put_contents($timestamp_file, time()+$timer);
}
$end_timestamp = file_get_contents($timestamp_file);
$current_timestamp = time();
$difference = $end_timestamp - $current_timestamp;

if($difference <= 0)
{
  echo 'time is up, BOOOOOOM';
  // execute your function here
  // reset timer by writing new timestamp into file
  file_put_contents($timestamp_file, time()+$timer);
}
else
{
  echo $difference.'s left...';
}
?>

You can use http://www.unixtimestamp.com/index.php to get familiar with the Unix Timestamp.

There are many ways that lead to rome, this is just one of the simple ones.

Outras dicas

you can use Cron Jobs Ex: Scheduling a Job For a Specific Time 30 08 10 06 * /home/sendtouser.php 30 – 30th Minute 08 – 08 AM 10 – 10th Day 06 – 6th Month (June) * – Every day of the week

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top