是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
当前回答
有多种方法可以做到这一点,但如果您更喜欢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
其他回答
header('位置:http://www.yoursite.com/new_page.html' );
使用echo从PHP输出JavaScript,这将完成任务。
echo '<script type="text/javascript">
window.location = "http://www.google.com/"
</script>';
除非缓冲页面输出,然后稍后检查重定向条件,否则在PHP中无法真正做到这一点。这可能太麻烦了。记住,头是从页面发送的第一件事。大多数重定向通常需要在页面的后面进行。为此,您必须缓冲页面的所有输出,并在稍后检查重定向条件。此时,您可以重定向页面用户header()或简单地回显缓冲的输出。
有关缓冲的更多信息(优点)
什么是输出缓冲?
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官方文档
您可以尝试使用PHP头函数进行重定向。您需要设置输出缓冲区,以便浏览器不会向屏幕发出重定向警告。
ob_start();
header("Location: " . $website);
ob_end_flush();