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

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

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


当前回答

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

其他回答

您可以尝试使用

header('Location:'.$your_url)

有关更多信息,请参阅php官方文档

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

以下是我的想法:

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

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

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

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

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

1.不带收割台

在这里你不会遇到任何问题

 <?php echo "<script>location.href='target-page.php';</script>"; ?>

2.使用带有exit()的头函数

<?php 
     header('Location: target-page.php');
     exit();
?>

但是如果你使用header函数,有时你会得到“警告”likeheader already send”来解析在发送头之前不回显或打印的问题,或者您可以在头函数之后简单地使用die()或exit()。

3.将头函数与ob_start()和ob_end_flush()一起使用

<?php
ob_start(); //this should be first line of your page
header('Location: target-page.php');
ob_end_flush(); //this should be last line of your page
?>

试试这个

 $url = $_SERVER['HTTP_REFERER'];
 redirect($url);