是否可以通过使用PHP将用户重定向到不同的页面?

假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/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>

其他回答

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中重定向,请使用:

<?php头('Location:URL');退出;?>

是的,您可以使用header()函数,

header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();

最好的做法是在header()函数之后立即调用exit()函数,以避免执行以下代码。

根据文档,在发送任何实际输出之前,必须调用header()。

您可以使用会话变量控制对页面的访问并授权有效用户:

<?php
    session_start();

    if (!isset( $_SESSION["valid_user"]))
    {
        header("location:../");
        exit();
    }

    // Page goes here
?>

http://php.net/manual/en/reserved.variables.session.php.

最近,我受到了网络攻击,并决定,我需要了解试图访问管理面板或web应用程序的保留部分的用户。

因此,我在文本文件中添加了IP地址和用户会话的日志访问,因为我不想打扰我的数据库。

使用header()函数发送HTTP位置标头:

header('Location: '.$newURL);

与一些人的想法相反,die()与重定向无关。仅当您希望重定向而不是正常执行时使用它。

文件example.php:

<?php
    header('Location: static.html');
    $fh = fopen('/tmp/track.txt', 'a');
    fwrite($fh, $_SERVER['REMOTE_ADDR'] . ' ' . date('c') . "\n");
    fclose($fh);
?>

三次执行的结果:

bart@hal9k:~> cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00

恢复-强制性die()/exit()是一些与实际PHP无关的都市传说。这与客户端“尊重”Location:标头无关。无论使用何种客户端,发送头都不会停止PHP执行。