是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
当前回答
以下是我的想法:
IMHO,重定向传入请求的最佳方法是使用位置标头
<?php
header("Location: /index.php");
?>
一旦执行了该语句并发出输出,浏览器将开始重新引导用户。但是,请确保在发送头之前没有任何输出(任何echo/var_dump),否则会导致错误。
虽然这是一种快速而肮脏的方式来实现最初的要求,但最终会成为一场SEO灾难,因为这种重定向总是被解释为301/302重定向,因此搜索引擎将始终将您的索引页视为重定向页,而不是登录页/主页。
因此,它会影响网站的SEO设置。
其他回答
这些答案中的大多数都忘记了一个非常重要的步骤!
header("Location: myOtherPage.php");
die();
离开这条至关重要的第二条线可能会让你最终登上《每日WTF》。问题是,浏览器不必尊重页面返回的标题,因此忽略了标题,页面的其余部分将在没有重定向的情况下执行。
用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)。
如果您在Apache上运行,也可以使用.htaccess进行重定向。
Redirect 301 / http://new-site.com/
有多种方法可以做到这一点,但如果您更喜欢php,我建议使用header()函数。
大体上
$your_target_url = “www.example.com/index.php”;
header(“Location : $your_target_url”);
exit();
如果你想把它提升一个档次,最好在函数中使用它。这样,您就可以在其中添加身份验证和其他检查元素。
让我们通过检查用户的级别来尝试。
因此,假设您已将用户的权限级别存储在名为u_auth的会话中。
在函数.php中
<?php
function authRedirect($get_auth_level,
$required_level,
$if_fail_link = “www.example.com/index.php”){
if ($get_auth_level != $required_level){
header(location : $if_fail_link);
return false;
exit();
}
else{
return true;
}
}
. . .
然后,您将为要验证的每个页面调用该函数。
类似于page.php或任何其他页面。
<?php
// page.php
require “function.php”
// Redirects to www.example.com/index.php if the
// user isn’t authentication level 5
authRedirect($_SESSION[‘u_auth’], 5);
// Redirects to www.example.com/index.php if the
// user isn’t authentication level 4
authRedirect($_SESSION[‘u_auth’], 4);
// Redirects to www.someotherplace.com/somepage.php if the
// user isn’t authentication level 2
authRedirect($_SESSION[‘u_auth’], 2, “www.someotherplace.com/somepage.php”);
. . .
参考文献;
http://php.net/manual/en/function.header.php
是的,可以使用PHP。我们将重定向到另一个页面。
尝试以下代码:
<?php
header("Location:./"); // Redirect to index file
header("Location:index.php"); // Redirect to index file
header("Location:example.php");
?>