是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
当前回答
Use:
<?php
$url = "targetpage"
function redirect$url(){
if (headers_sent()) == false{
echo '<script>window.location.href="' . $url . '";</script>';
}
}
?>
其他回答
现有答案汇总加上我自己的两分钱:
1.基本答案
您可以使用header()函数发送新的HTTP标头,但必须在任何HTML或文本之前(例如,在<!DOCTYPE…>声明之前)将其发送到浏览器。
header('Location: '.$newURL);
2.重要细节
die()或exit()
header("Location: https://example.com/myOtherPage.php");
die();
为什么应该使用die()或exit():每日WTF
绝对或相对URL
自2014年6月起,可以使用绝对URL和相对URL。请参阅RFC 7231,它取代了旧的RFC 2616,其中只允许绝对URL。
状态代码
PHP的“位置”标头仍然使用HTTP 302重定向代码,这是一个“临时”重定向,可能不是您应该使用的重定向。您应该考虑301(永久重定向)或303(其他)。
注意:W3C提到303标头与“许多HTTP/1.1之前的用户代理”不兼容。当前使用的浏览器都是HTTP/1.1用户代理。这对于许多其他用户代理(如蜘蛛和机器人)来说是不正确的。
3.文件
PHP中的HTTP Headers和header()函数
PHP手册的内容维基百科说什么W3C的说法
4.备选方案
您可以使用http_redirect($url);这需要安装PECL包PECL。
5.助手函数
此功能不包含303状态代码:
function Redirect($url, $permanent = false)
{
header('Location: ' . $url, true, $permanent ? 301 : 302);
exit();
}
Redirect('https://example.com/', false);
这更加灵活:
function redirect($url, $statusCode = 303)
{
header('Location: ' . $url, true, $statusCode);
die();
}
6.解决方法
如前所述,header()重定向只在写入任何内容之前生效。如果在midst HTML输出中调用,它们通常会失败。然后,您可以使用HTML标头解决方法(不是很专业!),如:
<meta http-equiv="refresh" content="0;url=finalpage.html">
甚至是JavaScript重定向。
window.location.replace("https://example.com/");
使用echo从PHP输出JavaScript,这将完成任务。
echo '<script type="text/javascript">
window.location = "http://www.google.com/"
</script>';
除非缓冲页面输出,然后稍后检查重定向条件,否则在PHP中无法真正做到这一点。这可能太麻烦了。记住,头是从页面发送的第一件事。大多数重定向通常需要在页面的后面进行。为此,您必须缓冲页面的所有输出,并在稍后检查重定向条件。此时,您可以重定向页面用户header()或简单地回显缓冲的输出。
有关缓冲的更多信息(优点)
什么是输出缓冲?
1.使用内置PHP函数header
a) 无参数的简单重定向
<?php
header('Location: index.php');
?>
b) 使用GET参数重定向
<?php
$id = 2;
header("Location: index.php?id=$id&msg=succesfully redirect");
?>
2.在PHP中使用JavaScript重定向
a) 无参数的简单重定向
<?php
echo "<script>location.href='index.php';</script>";
?>
b) 使用GET参数重定向
<?php
$id = 2;
echo "<script>location.href='index.php?id=$id&msg=succesfully redirect';</script>";
?>
1.不带收割台
在这里你不会遇到任何问题
<?php echo "<script>location.href='target-page.php';</script>"; ?>
2.使用带有exit()的头函数
<?php
header('Location: target-page.php');
exit();
?>
但是如果你使用header函数,有时你会得到“警告”likeheader already send”来解析在发送头之前不回显或打印的问题,或者您可以在头函数之后简单地使用die()或exit()。
3.将头函数与ob_start()和ob_end_flush()一起使用
<?php
ob_start(); //this should be first line of your page
header('Location: target-page.php');
ob_end_flush(); //this should be last line of your page
?>
header("Location: https://www.example.com/redirect.php");
直接重定向到此链接https://www.example.com/redirect.php
$redirect = "https://www.example.com/redirect.php";
header("Location: $redirect");
首先获取$redirect值,然后重定向到[value],如:https://www.example.com/redirect.php