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

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

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


当前回答

您可以尝试使用PHP头函数进行重定向。您需要设置输出缓冲区,以便浏览器不会向屏幕发出重定向警告。

ob_start();
header("Location: " . $website);
ob_end_flush();

其他回答

是的,可以使用PHP。我们将重定向到另一个页面。

尝试以下代码:

<?php
    header("Location:./"); // Redirect to index file
    header("Location:index.php"); // Redirect to index file
    header("Location:example.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()!

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.
?>

用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("Refresh: 3;url=https://theweek.com.br/índex.php");