drl2051 2017-08-14 04:48
浏览 126
已采纳

sleep()在php脚本中延迟整个页面

I want to display the echo for 5 seconds and redirect the page to login.html but when the page loads it takes 5 seconds instead of loading the page and waiting 5 sec then redirect.

<?php

  session_start();
  if (isset($_SESSION['name'])) {
      echo $_SESSION['name'];
  } else {
      echo "Login To Order";
      sleep(5);
      echo "<script type=\"text/javascript\">
                window.location.href = \"login.html\"; 
            </script>";
  }

?>

EDIT: ok this seems to delay it for 5 seconds but the code execution still continues further but I want it to stop =>echo for 5 seconds =>redirect to the other page.

             echo "Login To Order"; 
             echo "<script type=\"text/javascript\">
                      window.setTimeout(function() {
                              window.location.href=\"login.html\";
                              }, 5000);
                     </script>";
            echo "this should not be displayed";

echo "this should not be displayed"; my point here is that I have others codes below that I don't want to be executed in the else case.

  • 写回答

3条回答 默认 最新

  • dongyin5516 2017-08-14 04:59
    关注

    PHP pre-processes the page on the server, then sends the page to the client browser - sleeping on the server will rarely equate to a delay on the client

    Put the delay on the client side using setTimeout

    <?php
        session_start(); 
        if (isset($_SESSION['name'])){
            echo $_SESSION['name'];
        } else {
    ?>
            Login To Order
            <script>
                setTimeout(function() {
                    window.location.href="login.html";
                }, 5000);
            </script>
    <?php
            exit(0);
        }
    ?>
    

    note how you can switch PHP preprocessing off ?> to make the script easier to write, then switch PHP back on <?php

    or even simpler, use a HTTP header to do the work for you

    <?php
        session_start(); 
        if (isset($_SESSION['name'])){
            echo $_SESSION['name'];
        } else {
            header("refresh:5; url=login.html"); 
    ?>
            Login To Order
    <?php
            exit(0);
        }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站