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

假设用户转到www.example.com/page.php,我想将其重定向到www.example.com/index.php,那么在不使用元刷新的情况下,我如何做到这一点?有可能吗?

这甚至可以保护我的页面免受未授权用户的攻击。


当前回答

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()!

其他回答

header("Location: https://www.example.com/redirect.php");

直接重定向到此链接https://www.example.com/redirect.php

$redirect = "https://www.example.com/redirect.php";
header("Location: $redirect");

首先获取$redirect值,然后重定向到[value],如:https://www.example.com/redirect.php

Use:

<?php header('Location: another-php-file.php'); exit(); ?>

或者,如果您已经打开了PHP标记,请使用以下命令:

header('Location: another-php-file.php'); exit();

您还可以重定向到外部页面,例如:

header('Location: https://www.google.com'); exit();

确保包含exit()或includedie()。

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

<?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地址和用户会话的日志访问,因为我不想打扰我的数据库。

用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)。

这些答案中的大多数都忘记了一个非常重要的步骤!

header("Location: myOtherPage.php");
die();

离开这条至关重要的第二条线可能会让你最终登上《每日WTF》。问题是,浏览器不必尊重页面返回的标题,因此忽略了标题,页面的其余部分将在没有重定向的情况下执行。