是否有可能通过使用PHP将用户重定向到一个不同的页面?
假设用户到了www.example.com/page.php
,我想把他们重定向到www.example.com/index.php
,我如何在不使用元刷新的情况下做到这一点?这可能吗?
这甚至可以保护我的页面不被未经授权的用户访问。
使用header()
函数来发送HTTPLocation
标头。
header('Location: '.$newURL);
与某些人的想法相反,die()
与重定向没有任何关系。只有在你想重定向而不是正常执行时才使用它。
文件 example.php:
<?php
header('Location: static.html');
$fh = fopen('/tmp/track.txt', 'a');
fwrite($fh, $_SERVER['REMOTE_ADDR'] . ' ' . date('c') . "\n");
fclose($fh);
?>
三次执行的结果。
bart@hal9k:~> cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00
恢复—强制性的die()
/exit()
是一些城市传说,与实际的PHP没有关系。它与客户端尊重Location:
头文件无关。发送头信息不会停止 PHP 的执行,不管使用的是什么客户端。
function Redirect($url, $permanent = false)
{
if (headers_sent() === false)
{
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
Redirect('http://www.google.com/', false);
不要忘记die()/exit()!