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

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

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


当前回答

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>";
   ?>

其他回答

我已经回答了这个问题,但我会再回答一次,因为在此期间我了解到,如果您在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)

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

这些答案中的许多都是正确的,但它们假设您有一个绝对的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

我喜欢数秒后的重定向

<?php

header("Refresh: 3;url=https://theweek.com.br/índex.php");

使用echo从PHP输出JavaScript,这将完成任务。

echo '<script type="text/javascript">
           window.location = "http://www.google.com/"
      </script>';

除非缓冲页面输出,然后稍后检查重定向条件,否则在PHP中无法真正做到这一点。这可能太麻烦了。记住,头是从页面发送的第一件事。大多数重定向通常需要在页面的后面进行。为此,您必须缓冲页面的所有输出,并在稍后检查重定向条件。此时,您可以重定向页面用户header()或简单地回显缓冲的输出。

有关缓冲的更多信息(优点)

什么是输出缓冲?