有可能通过使用PHP将用户重定向到不同的页面吗?
假设用户转到www.example.com/page.php
,我想将它们重定向到www.example.com/index.php
,如果不使用元刷新,我该如何进行重定向呢? 有可能吗?
这甚至可以保护我的页面免受未经授权的用户的攻击。
现有答案的总结加上我自己的两分钱:
您可以使用header()
函数发送一个新的HTTP头,但它必须在任何HTML或文本之前(例如,在声明之前)发送到浏览器。
header('Location: '.$newURL);
die()或exit()
header("Location: http://example.com/myOtherPage.php");
die();
为什么要使用die()
或exit()
:每日WTF
绝对或相对URL
自2014年6月起,绝对URL和相对URL都可以使用。 请参阅RFC7231,它取代了旧的RFC2616,在旧的RFC2616中只允许绝对URL。
状态代码
PHP的“location”-头仍然使用HTTP302-redirect代码,但这不是您应该使用的代码。 您应该考虑301(永久重定向)或303(其他)。
注意:W3C提到303头与“许多HTTP/1.1之前的用户代理程序不兼容。当前使用的浏览器都是HTTP/1.1用户代理程序。对于许多其他用户代理程序(如蜘蛛和机器人)来说,这是不正确的。
HTTP头和PHP中的header()
函数
您可以使用HTTP_REDIRECT($URL);
的替代方法,该方法需要安装PECL包PECL。
此函数不包含303状态代码:
function Redirect($url, $permanent = false)
{
header('Location: ' . $url, true, $permanent ? 301 : 302);
exit();
}
Redirect('http://example.com/', false);
这样更灵活:
function redirect($url, $statusCode = 303)
{
header('Location: ' . $url, true, $statusCode);
die();
}
如前所述,header()
只重定向写出任何内容之前的工作。 如果在HTML输出中调用它们,它们通常会失败。 那么您可能会使用HTML头变通方法(不是很专业!) 如:
<meta http-equiv="refresh" content="0;url=finalpage.html">
或者JavaScript重定向。
window.location.replace("http://example.com/");
使用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
Resumining-obilitatorydie()
/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()!