PHP服务器端倒计时

时间:2018-03-09 11:38:13

标签: javascript php jquery mysql cron

我有什么方法可以使用PHP在SERVER端制作倒数计时器吗?

像这样:

  • 倒计时器应该等于进入网站的任何人
  • 一旦计时器达到零,就应该执行一个代码。但只有一次。

想象一下头奖网站,一旦计时器达到零,一些查询就需要执行。但是如果我们在网站上有50个人,则会执行50个查询。所以它需要是服务器端的。我该如何解决?

每秒使用cronjobs?在VPS上打开一个网页,在“秘密”链接上自行处理计时器? 某种live-php脚本?

1 个答案:

答案 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代码。我知道这不是完整的解决方案,但它至少是其中的一部分:)