是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
当前回答
您可以尝试使用
header('Location:'.$your_url)
有关更多信息,请参阅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
function Redirect($url, $permanent = false)
{
if (headers_sent() === false)
{
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
Redirect('http://www.google.com/', false);
别忘了die()/ext()!
用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()函数。
大体上
$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' );