duanlianyun0462 2016-03-21 08:47
浏览 43
已采纳

sleep()如何在PHP中运行

Please excuse what may seem like a very simple question and may lack of understanding of how PHP/sleep() works, but I was after some guidance on the following code:

<?php
$time_now = time();
echo "Time Now : " . $time_now;
sleep(10);
$time_then = time();
echo "<br>Time Then : " . $time_then;
?>

I was expecting this code to output the current time, then wait 10 seconds, then output the time 10 seconds later.

Instead it waits the 10 seconds set and outputs both the times at the same time. The times ARE correct in that the 'Time Now' is when I executed the code, and the 'Time Then' is 10 seconds later, but it does not respond how I expected (output Time Now, wait 10 seconds, then continue to execute the code and show 'Time Then').

Given that my understanding is clearly incorrect, is it possible to achieve this? Or would I be better to trigger another file to load what I want to do as follows:

File 1

<?php
$time_now = time();
echo "Time Now : " . $time_now;
header('Location: page2.php');
?>

File 2

<?php
sleep(10);
$time_then = time();
echo "<br>Time Then : " . $time_then;
?>

Thank you.

  • 写回答

2条回答 默认 最新

  • dongou0524 2016-03-21 08:48
    关注

    You need to use the flush function of PHP, to get the excepted result.

    PHP gives you the output, when script has finished. If you want to show the result in real time, you need to flush the output buffer.

    $time_now = time();
    echo "Time Now : " . $time_now;
    flush();
    sleep(10);
    $time_then = time();
    echo "<br>Time Then : " . $time_then;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用