doulang6013 2018-03-09 11:38
浏览 70

PHP服务器端倒计时

Is there any way I can use PHP to make a countdown timer on the SERVER side?

Like this:

  • The countdown timer should be equal to anyone entering the website
  • Once the timer hits zero, a code should execute. But only once.

Imagine a jackpot website, once the timer hits zero some queries needs to execute. But if we have 50 people on the site, then 50 queries would execute. So it needs to be server-side. How can I solve that?

Using cronjobs for every second? A web-page open on the VPS that handles the timer by itself on a "secret" link? Some sort of live-php script?

  • 写回答

1条回答 默认 最新

  • douyaju4259 2018-03-09 11:59
    关注

    PHP countdown can be coded like this:

    //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.
    }
    

    Beacuse of PHP nature, this 'timer check' will occur only on page load. If you want to trigger some code execution precisely when counter hits 0 you should use JavaScript for detecting coundtdown pass and trigger with AJAX some PHP code. I know this is not complete solution but it's at least part of it :)

    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能