Redirect 10 second Countdown

后端 未结 4 448
执念已碎
执念已碎 2020-12-13 10:58

I have a page which redirects a user after 10 seconds with the following code.


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

    You cannot do this with pure PHP - but javascript is your friend here.

    Change your HTML to put the number of seconds in a span:

    <b><span id="count">10</span> Seconds</b>
    

    Then remove your meta tag and use this javascript:

    var count = 10;
    function decrement() {
        count--;
        if(count == 0) {
            window.location = 'login.php';
        }
        else {
            document.findElementById("count").innerHTML = "" + count;
            setTimeout("decrement", 1000);
        }
    }
    setTimeout("decrement", 1000);
    

    This will decrement the count on the page every second and then redirect to login.php when the counter reaches 0.

    0 讨论(0)
  • 2020-12-13 11:29

    header("Refresh: 2; url=$your_url");

    Remember not to put any html content before the header.

    0 讨论(0)
  • 2020-12-13 11:32

    The following will redirect the user right away to login.php

    <?php
    header('Location: login.php'); // redirects the user instantaneously.
    exit;
    ?>
    

    You can use the following to delay the redirection by X seconds but there is no graphical countdown (thanks to user1111929):

    <?php
    header('refresh: 10; url=login.php'); // redirect the user after 10 seconds
    #exit; // note that exit is not required, HTML can be displayed.
    ?>
    

    If you want a graphical countdown, here's a sample code in JavaScript:

    <p>You will be redirected in <span id="counter">10</span> second(s).</p>
    <script type="text/javascript">
    function countdown() {
        var i = document.getElementById('counter');
        if (parseInt(i.innerHTML)<=0) {
            location.href = 'login.php';
        }
    if (parseInt(i.innerHTML)!=0) {
        i.innerHTML = parseInt(i.innerHTML)-1;
    }
    }
    setInterval(function(){ countdown(); },1000);
    </script>
    
    0 讨论(0)
  • 2020-12-13 11:40

    I would use javascript for this

    var counter = 10;
    setInterval(function() {
        counter--;
        if(counter < 0) {
            window.location = 'login.php';
        } else {
            document.getElementById("count").innerHTML = counter;
             }
    }, 1000);​
    

    Update: http://jsfiddle.net/6wxu3/1/

    0 讨论(0)
提交回复
热议问题