是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
当前回答
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>";
?>
其他回答
这些答案中的大多数都忘记了一个非常重要的步骤!
header("Location: myOtherPage.php");
die();
离开这条至关重要的第二条线可能会让你最终登上《每日WTF》。问题是,浏览器不必尊重页面返回的标题,因此忽略了标题,页面的其余部分将在没有重定向的情况下执行。
您可以使用以下JavaScript方法
self.location=“http://www.example.com/index.php";window.location.href=“http://www.example.com/index.php";文档位置href='http://www.example.com/index.php';window.location.replace(“http://www.example.com/index.php");
在语义网络的前夜,正确性是需要考虑的问题。不幸的是,PHP的“Location”标头仍然使用HTTP302重定向代码,严格来说,这不是最佳的重定向代码。它应该使用的是303。
W3C很高兴地提到,303标头与“许多HTTP/1.1之前的用户代理”不兼容,这相当于当前使用的浏览器。因此,302是一件遗物,不应该使用。
…或者你可以像其他人一样忽略它。。。
Use:
<?php
header('Location: redirectpage.php');
header('Location: redirectpage.php');
exit();
echo "<script>location.href='redirectpage.php';</script>";
?>
这是一个普通的PHP重定向,但您可以通过以下代码在几秒钟内创建一个重定向页面:
<?php
header('refresh:5;url=redirectpage.php '); // Note: here 5 means 5 seconds wait for redirect.
?>
您可以尝试使用
header('Location:'.$your_url)
有关更多信息,请参阅php官方文档