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条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记