是否可以通过使用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>";
   ?>

其他回答

header('位置:http://www.yoursite.com/new_page.html' );

如果您在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头函数进行重定向。您需要设置输出缓冲区,以便浏览器不会向屏幕发出重定向警告。

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

以下是我的想法:

IMHO,重定向传入请求的最佳方法是使用位置标头

<?php
    header("Location: /index.php");
?>

一旦执行了该语句并发出输出,浏览器将开始重新引导用户。但是,请确保在发送头之前没有任何输出(任何echo/var_dump),否则会导致错误。

虽然这是一种快速而肮脏的方式来实现最初的要求,但最终会成为一场SEO灾难,因为这种重定向总是被解释为301/302重定向,因此搜索引擎将始终将您的索引页视为重定向页,而不是登录页/主页。

因此,它会影响网站的SEO设置。