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 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站