Redirect with Timer in PHP?

前端 未结 11 2057
刺人心
刺人心 2020-12-28 11:49

How can I make a redirect with PHP after say 10 seconds...

I have read alot about it, seems like it would be better with javascript. But PHP would save me alot of co

相关标签:
11条回答
  • 2020-12-28 12:23

    I managed to do it with a simple function on PHP

    function RedirectToURL($url, $waitmsg = 0.4)
    {
        header("Refresh:$waitmsg; URL= $url");
        exit;
    }
    

    and you call from your PHP for waiting 2 seconds before redirect. Note that $waitmsg = 0.4 is used for defining the default value.

    RedirectToURL("http://website.php", 2);
    

    If you want to redirect after a form submit, you can try

    if(isset($_POST['submitted']))
    {
           echo '<div style="text-align:center; margin-left:auto; margin-right:auto"><br><br>Sucess. Thanks for contribution.</div>';
           RedirectToURL("http://thewebsiteilookforaftersubmit", 2); // I want to wait 2 seconds and not 0.4 as defined by default
    }
    
    0 讨论(0)
  • 2020-12-28 12:25

    You can cause your PHP script to sleep for 10 seconds,

    sleep(10);
    

    but this will appear to the end-user as a non-responsive server. The best option is to use either a meta refresh,

    <meta http-equiv="refresh" content="10;url=http://google.com">
    

    or javascript.

    setTimeout(function(){
      window.location = "http://google.com";
    }, 10000);
    

    Found in the comments from Daniel:

    header('Refresh: 10; URL=http://yoursite.com/page.php');
    

    would be ideal for this situation, as it requires no Javascript or HTML.

    0 讨论(0)
  • 2020-12-28 12:28

    That is a bad idea to make PHP script sleeping. Actually it is a way to DoS your server easily ;) PHP script in memory is consuming enough resources especially if it is working as CGI.

    0 讨论(0)
  • 2020-12-28 12:33

    PHP is the probably wrong technology for this as it runs server-side and won't provide useful feedback to the user during the delay.

    This isn't a lot of coding in Javascript. See this link for a very easy way to implement this on your page

    0 讨论(0)
  • 2020-12-28 12:38

    Create a file, for example: "go.php", with code

    <?php
    $site = $_GET['iam'];
    sleep(5);
    Header ("Location: ".$site."");
    exit();
    ?>
    
    <a href="http://whatever.com/go.php?iam=http://google.com">Link</a>
    

    or like this, without "sleep"

    <?php
    $site = $_GET['iam'];
    Header('HTTP/1.1 301 Moved Permanently');
    Header("Refresh: 10; URL=".$site."");
    exit();
    ?>
    
    <a href="http://whatever.com/go.php?iam=http://google.com">Link</a>
    
    0 讨论(0)
提交回复
热议问题