PHP服务器端计时器

PHP服务器端计时器

问题描述:

我需要制作一个带有倒计时计时器的页面.我希望计时器在服务器端,这意味着每当用户打开页面时,所有用户的计数器始终处于同一时间.当计时器为零时,我需要能够运行另一个脚本,这会与重置计时器一起做一些事情.

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.

我怎么能用php做类似的事情?

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

从用户何时打开页面"判断,页面是否应该具有自动更新机制?如果这不是您的意思,请查看AJAX(如注释中所述),或更简单地查看HTML META刷新.或者,使用PHP和header()

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/zh/function .header.php

方法,也在此处进行描述:

method, described also here:

使用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.

让我们假设您的脚本文件夹中有一个包含unix时间戳的文件,您可以执行以下操作:

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...';
}
?>

您可以使用 http://www.unixtimestamp.com/index.php 来熟悉Unix时间戳.

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.