douhan8009 2012-09-06 11:19
浏览 56
已采纳

PHP问题与sleep()和重定向

I have the following dumb code:

<?

echo "<html><br><br><br><div id='loading'><p><img src='loader.gif'> Please wait 6 seconds...</p></div></html>";
sleep(6);
header('Location: http://google.com/');

?>

Why doesn't the HTML piece of code show up in the browser before sleeping 6 seconds and then redirecting? The codes doesn't output the HTML code at all, waits 6 seconds then sends me to the location. What do I do wrong?

  • 写回答

4条回答 默认 最新

  • duanbo2048 2012-09-06 11:22
    关注

    You would need to do something like (this won't work):

    <?php
    
    echo "<html><br><br><br><div id='loading'><p><img src='loader.gif'> Please wait 6 seconds...</p></div></html>";
    @ob_flush(); //flush the output buffer
    flush(); //flush anything else
    sleep(6); //wait
    header('Location: http://google.com/'); //redirect
    
    ?>
    

    However: This won't work as expected, you cannot redirect the browser after sending content (PHP will throw and error and tell you this)

    Instead you should:

    <?php
    
    echo "<html><meta http-equiv=\"refresh\" content=\"6;URL='http://YOURURL.com/'\"><br><br><br><div id='loading'><p><img src='loader.gif'> Please wait 6 seconds...</p></div></html>";
    
    ?>
    

    Where the <meta http-equiv="refresh" content="6;URL='http://YOURURL.com/'"> tag is an HTML tag to tell the browser to change to the provided url after 6 seconds

    To avoid adding the meta tag, you could also do this:

    <?php
    header('Refresh: 6;URL=http://www.YOURURL.com/');
    echo "<html><br><br><br><div id='loading'><p><img src='loader.gif'> Please wait 6 seconds...</p></div></html>"
    ?>
    

    But to be safe you should add both the header and the meta tag!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 等差数列中的素数个数
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证