header location delay

前端 未结 7 1960
攒了一身酷
攒了一身酷 2020-12-06 02:49

I have the following php code which I want to add a delay too:



        
相关标签:
7条回答
  • 2020-12-06 03:21

    You cannot do this with a HTTP location redirect, as this redirect will happen as soon as the browser gets the header. Instead, use a refresh redirect in the header:

    header( "Refresh:5; url=http://www.example.com/page2.php", true, 303);
    

    This should work on modern browsers, however it is not standardized, so to get the equivalent functionality would be do use a meta refresh redirect (meaning you'd have to output a full HTML too):

    <meta http-equiv="refresh" content="5;url=http://www.example.com/page2.php"> 
    

    From the Wikipedia page:

    Used in redirection, or when a new resource has been created. This refresh redirects after X seconds. This is a proprietary, non-standard header extension introduced by Netscape and supported by most web browsers.

    0 讨论(0)
  • 2020-12-06 03:34

    You have to modify your code like this:

    <?php
    
        echo "Message has been sent.";
        sleep(5);
        header("Location: page2.php", true, 303);
        exit;
    ?>
    
    0 讨论(0)
  • 2020-12-06 03:36

    You won't be able to see the message if you're using a header(Location) redirect. In fact, that redirect shouldn't work at all since output starts before the headers are sent. Instead, you should echo a meta tag refresh with a delay, like this echo '<meta http-equiv="refresh" content="5;URL=\'http://example.com/\'">';

    which will have a delay of five seconds. Alternatively, (and more properly) you could output a JS redirect, as the meta refresh tag is deprecated.

    0 讨论(0)
  • 2020-12-06 03:38

    i don't know if it helps but as i was dealing with the same issue in a form which need to be clean after the submission of the message, i found this answer that explains that you could change the value input to be empty.

    This is the answer: How do I reset the value of a text input when the page reloads?

    and this is how i fix my issue, using my class .form-control

    $(document).ready(function() {
       $(".form-control").val('');
    });
    
    0 讨论(0)
  • 2020-12-06 03:39

    This is what worked for me... I'm using the latest PHP version 7.3.3 on WAMPP for Windows...

    <?php
    
    $name = $_POST['name'] ?? null; 
    
    if(empty(trim($name))){
        header("location: http://localhost/testsite/index.php");
    }
    
    echo 'Greetings '. $_POST['name'].', how can I help you?';
    
    echo '<meta http-equiv="refresh" content="5;URL=\'http://localhost/testsite/index.php\'">';
    

    I hope this helps.

    0 讨论(0)
  • 2020-12-06 03:42

    Do the redirect using client-side scripting:

    <script>
    window.setTimeout(function() {
        window.location = 'page2.php';
      }, 5000);
    </script>
    <p>Message has been sent.</p>
    
    0 讨论(0)
提交回复
热议问题