我有一个页面,它在 10 秒后使用以下代码重定向用户。
<META HTTP-EQUIV="refresh" CONTENT="10;URL=login.php">
然后我有这段代码,它在 PHP 中被回显,并希望"10"(秒)动态倒计时为 10、9、8、7......这样用户可以看到页面重定向之前的剩余秒数。
echo "We cant find you on the system. <br/> Please return to the <b><a href='login.php'>Login</a></b> page and ensure that <br/>you have entered your details correctly.
<br>
<br>
<b>Warning</b>: You willl be redirected back to the Login Page <br> in <b>10 Seconds</b>";
我想知道是否有一种方法可以在 PHP 中完成此操作,如果没有,实现相同目标的最佳方法是什么?
以下内容将立即将用户重定向到login.php
<?php
header('Location: login.php'); // redirects the user instantaneously.
exit;
?>
您可以使用以下命令将重定向延迟 X 秒,但没有图形倒计时(感谢 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.
?>
如果你想要一个图形倒计时,这里有一个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>
我会为此使用 javascript
var counter = 10;
setInterval(function() {
counter--;
if(counter < 0) {
window.location = 'login.php';
} else {
document.getElementById("count").innerHTML = counter;
}
}, 1000);
更新:http://jsfiddle.net/6wxu3/1/
你不能用纯PHP做到这一点 - 但javascript是你的朋友。
更改您的 HTML 以将秒数放入span
:
<b><span id="count">10</span> Seconds</b>
然后删除您的meta
标签并使用此 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);
这将每秒递减页面上的计数,然后在计数器达到 0 时重定向到 login.php
。
header("Refresh: 2; url=$your_url");
切记不要在标题之前放置任何 html 内容。
这对于 3 秒重定向页面重定向到索引页面的效果非常好,但不会在屏幕上显示倒数计时器。
<?php
echo "New record has been added successfully ! This page will redirect in 3 seconds";
header('refresh: 3; url=index.php');
?>