drl2051 2017-08-13 20:48
浏览 127
已采纳

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-13 20: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条)
编辑
预览

报告相同问题?