我有什么方法可以使用PHP在SERVER端制作倒数计时器吗?
像这样:
想象一下头奖网站,一旦计时器达到零,一些查询就需要执行。但是如果我们在网站上有50个人,则会执行50个查询。所以它需要是服务器端的。我该如何解决?
每秒使用cronjobs?在VPS上打开一个网页,在“秘密”链接上自行处理计时器? 某种live-php脚本?
答案 0 :(得分:0)
PHP倒计时可以这样编码:
//You must call the function session_start() before
//you attempt to work with sessions in PHP!
session_start();
//Check to see if our countdown session
//variable has been initialized.
if(!isset($_SESSION['countdown'])){
//Set the countdown to 120 seconds.
$_SESSION['countdown'] = 120;
//Store the timestamp of when the countdown began.
$_SESSION['time_started'] = time();
}
//Get the current timestamp.
$now = time();
//Calculate how many seconds have passed since
//the countdown began.
$timeSince = $now - $_SESSION['time_started'];
//How many seconds are remaining?
$remainingSeconds = abs($_SESSION['countdown'] - $timeSince);
//Print out the countdown.
echo "There are $remainingSeconds seconds remaining.";
//Check if the countdown has finished.
if($remainingSeconds < 1){
//Finished! Do something.
}
由于PHP的性质,这种'计时器检查'仅在页面加载时发生。如果你想在计数器命中0时准确触发一些代码执行,你应该使用JavaScript来检测coundtdown传递并使用AJAX触发一些PHP代码。我知道这不是完整的解决方案,但它至少是其中的一部分:)