是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
是否可以通过使用PHP将用户重定向到不同的页面?
假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?
这甚至可以保护我的页面免受未授权用户的攻击。
当前回答
使用以下代码:
header("Location: /index.php");
exit(0);
其他回答
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>";
?>
如果您在Apache上运行,也可以使用.htaccess进行重定向。
Redirect 301 / http://new-site.com/
我已经回答了这个问题,但我会再回答一次,因为在此期间我了解到,如果您在CLI中运行(重定向无法发生,因此不应该exit()),或者您的Web服务器以(F)CGI的形式运行PHP(它需要预先设置的Status标头才能正确重定向),则会有一些特殊情况。
function Redirect($url, $code = 302)
{
if (strncmp('cli', PHP_SAPI, 3) !== 0)
{
if (headers_sent() !== true)
{
if (strlen(session_id()) > 0) // If using sessions
{
session_regenerate_id(true); // Avoids session fixation attacks
session_write_close(); // Avoids having sessions lock other requests
}
if (strncmp('cgi', PHP_SAPI, 3) === 0)
{
header(sprintf('Status: %03u', $code), true, $code);
}
header('Location: ' . $url, true, (preg_match('~^30[1237]$~', $code) > 0) ? $code : 302);
}
exit();
}
}
我还处理了支持不同HTTP重定向代码(301、302、303和307)的问题,这在我之前的回答的评论中得到了解决。以下是描述:
301-永久移动302-找到303-见其他307-临时重定向(HTTP/1.1)
使用标头函数进行路由
<?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("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)。