是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
当前回答
这些答案中的许多都是正确的,但它们假设您有一个绝对的URL,而事实可能并非如此。如果您想使用相对URL并生成其余部分,那么可以执行以下操作。。。
$url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
$url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
$url .= '/your-relative/path-goes/here/'; // <-- Your relative path
header('Location: ' . $url, true, 302); // Use either 301 or 302
其他回答
用PHP重定向的最佳方法是以下代码。。。
header("Location: /index.php");
确保没有代码在
header("Location: /index.php");
所有代码必须在上述行之前执行。
认为
案例1:
echo "I am a web developer";
header("Location: /index.php");
它将正确重定向到该位置(index.php)。
案例2:
return $something;
header("Location: /index.php");
上述代码不会重定向到该位置(index.php)。
使用标头函数进行路由
<?php
header('Location: B.php');
exit();
?>
假设我们想要从A.php文件路由到B.php,那么我们需要借助<button>或<A>。让我们看一个例子
<?php
if(isset($_GET['go_to_page_b'])) {
header('Location: B.php');
exit();
}
?>
<p>I am page A</p>
<button name='go_to_page_b'>Page B</button>
B.php语言
<p> I am Page B</p>
我喜欢数秒后的重定向
<?php
header("Refresh: 3;url=https://theweek.com.br/índex.php");
这些答案中的大多数都忘记了一个非常重要的步骤!
header("Location: myOtherPage.php");
die();
离开这条至关重要的第二条线可能会让你最终登上《每日WTF》。问题是,浏览器不必尊重页面返回的标题,因此忽略了标题,页面的其余部分将在没有重定向的情况下执行。
是的,您可以使用header()函数,
header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();
最好的做法是在header()函数之后立即调用exit()函数,以避免执行以下代码。
根据文档,在发送任何实际输出之前,必须调用header()。