1440

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

假设用户去www.example.com/page.php并且我想将他们重定向到www.example.com/index.php,如果不使用元刷新,我将如何做到这一点?可能吗?

这甚至可以保护我的页面免受未经授权的用户的侵害。

4

33 回答 33

1902

现有答案的摘要加上我自己的两分钱:

1. 基本答案

您可以使用该header()函数发送新的 HTTP 标头,但这必须在任何 HTML 或文本之前发送到浏览器(<!DOCTYPE ...>例如,在声明之前)。

header('Location: '.$newURL);

2. 重要细节

死()退出()

header("Location: https://example.com/myOtherPage.php");
die();

为什么你应该使用die()or exit(): The Daily WTF

绝对或相对 URL

自 2014 年 6 月起,可以使用绝对 URL 和相对 URL。请参阅RFC 7231,它取代了旧的RFC 2616,其中只允许使用绝对 URL。

状态码

PHP 的“Location”-header 仍然使用HTTP 302 -redirect 代码,这是一种“临时”重定向,可能不是您应该使用的重定向。您应该考虑301(永久重定向)或303(其他)。

注意:W3C 提到303 标头与“许多 HTTP/1.1 之前的用户代理不兼容。当前使用的浏览器都是 HTTP/1.1 用户代理。对于许多其他用户代理,如蜘蛛和机器人,情况并非如此。

3. 文档

HTTP 标头和header()PHP 中的函数

4. 替代品

您可以使用http_redirect($url);需要安装PECL 包 pecl的替代方法。

5. 辅助函数

此函数不包含 303 状态代码:

function Redirect($url, $permanent = false)
{
    header('Location: ' . $url, true, $permanent ? 301 : 302);

    exit();
}

Redirect('https://example.com/', false);

这更灵活:

function redirect($url, $statusCode = 303)
{
   header('Location: ' . $url, true, $statusCode);
   die();
}

6. 解决方法

如前所述header(),重定向仅在写出任何内容之前起作用。如果在 HTML输出中调用它们通常会失败。然后,您可以使用 HTML 标头解决方法(不是很专业!),例如:

 <meta http-equiv="refresh" content="0;url=finalpage.html">

甚至是 JavaScript 重定向。

window.location.replace("https://example.com/");
于 2009-04-20T14:19:24.067 回答
143

使用该header()函数发送HTTPLocation标头

header('Location: '.$newURL);

与某些人的想法相反,die()与重定向无关。当您想重定向而不是正常执行时才使用它。

文件example.php

<?php
    header('Location: static.html');
    $fh = fopen('/tmp/track.txt', 'a');
    fwrite($fh, $_SERVER['REMOTE_ADDR'] . ' ' . date('c') . "\n");
    fclose($fh);
?>

三个处决的结果:

bart@hal9k:~> cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00

Resuming - 强制die()/exit()是一些与实际 PHP 无关的都市传说。它与客户“尊重”标头无关Location:。无论使用何种客户端,发送标头都不会停止 PHP 执行。

于 2009-04-20T14:14:11.130 回答
123
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()/ exit()

于 2009-04-20T14:19:11.010 回答
108

Output JavaScript from PHP using echo, which will do the job.

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

You can't really do it in PHP unless you buffer the page output and then later check for redirect condition. That might be too much of a hassle. Remember that headers are the first thing that is sent from the page. Most of the redirect is usually required later in the page. For that you have to buffer all the output of the page and check for redirect condition later. At that point you can either redirect page user header() or simply echo the buffered output.

For more about buffering (advantages)

What is output buffering?

于 2014-06-27T07:24:59.483 回答
107

1.没有标题

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

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

2.使用header函数exit()

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

但是,如果您使用标头功能,那么有时您会收到“标头已发送的警告”来解决在发送标头之前不回显或打印的问题,或者您可以简单地使用标头功能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
?>
于 2017-04-13T12:44:35.100 回答
57

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

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

离开那条重要的第二条线可能会让你最终出现在The Daily WTF上。问题是浏览器不必尊重页面返回标题,因此忽略标题,页面的其余部分将在没有重定向的情况下执行。

于 2009-04-20T14:24:47.457 回答
34

利用:

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

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

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

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

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

确保包含exit()或包含die().

于 2016-05-16T13:12:55.453 回答
25

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

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

于 2016-09-09T10:48:33.533 回答
19

其中许多答案是正确的,但他们假设您有一个绝对 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
于 2014-01-15T04:21:54.140 回答
18

使用以下代码:

header("Location: /index.php");
exit(0);   
于 2015-01-12T11:03:32.137 回答
17

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

于 2009-04-20T14:14:41.643 回答
14

我已经回答了这个问题,但我会再做一次,因为与此同时我了解到如果您在 CLI 中运行(重定向不会发生,因此不应该exit())或者您的网络服务器是将 PHP 作为 (F)CGI 运行(它需要预先设置的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 重定向代码(301302和)的问题303307正如我在上一个答案的评论中所解决的那样。以下是说明:

  • 301 - 永久移动
  • 302 - 找到
  • 303 - 见其他
  • 307 - 临时重定向 (HTTP/1.1)
于 2011-04-28T21:31:36.370 回答
12

要将访问者重定向到另一个页面(在条件循环中特别有用),只需使用以下代码:

<?php
    header('Location: mypage.php');
?>

在这种情况下,mypage.php是您希望将访问者重定向到的页面地址。该地址可以是绝对地址,也可以包含以下格式的参数:mypage.php?param1=val1&m2=val2)

相对/绝对路径

在处理相对或绝对路径时,最好从服务器的根目录 (DOCUMENT_ROOT) 选择绝对路径。使用以下格式:

<?php
    header('Location: /directory/mypage.php');
?>

如果目标页面位于另一台服务器上,则包含完整的 URL:

<?php
    header('Location: http://www.ccm.net/forum/');
?>

HTTP 标头

根据 HTTP 协议,HTTP 标头必须发送before任何类型的内容。这意味着在标题之前不应该发送任何字符——甚至是空格!

临时/永久重定向

默认情况下,上述重定向类型是临时的。这意味着搜索引擎(例如 Google 搜索)在编制索引时不会考虑重定向。

如果您想通知搜索引擎某个页面已永久移动到另一个位置,请使用以下代码:

<?
    header('Status: 301 Moved Permanently', false, 301);
    header('Location: new_address');
?>

例如,此页面有以下代码:

<?
    header('Status: 301 Moved Permanently', false, 301);
    header('Location: /pc/imprimante.php3');
    exit();
?>

当您单击上面的链接时,您将自动重定向到此页面。此外,它是永久重定向(状态:301 永久移动)。因此,如果您在 Google 中输入第一个 URL,您将自动被重定向到第二个重定向链接。

PHP代码解读

位于 header() 之后的 PHP 代码将由服务器解释,即使访问者移动到重定向中指定的地址也是如此。在大多数情况下,这意味着您需要一个方法来遵循header()函数的exit()功能,以减少服务器的负载:

<?
    header('Status: 301 Moved Permanently', false, 301);
    header('Location: address');
    exit();
?>
于 2018-02-13T09:26:52.680 回答
9

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

试试下面的代码:

<?php
    header("Location:./"); // Redirect to index file
    header("Location:index.php"); // Redirect to index file
    header("Location:example.php");
?>
于 2017-06-08T06:34:37.683 回答
9

利用:

<?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.
?>
于 2017-08-18T06:46:30.547 回答
7

在语义网的前夜,正确性是需要考虑的事情。不幸的是,PHP 的“Location”-header 仍然使用HTTP 302 -redirect 代码,严格来说,这并不是最好的重定向代码。它应该使用的那个是303那个。

W3C 非常友好地提到303 标头与“许多 HTTP/1.1 之前的用户代理”不兼容,这相当于当前使用没有浏览器。所以,302是遗物,应该使用。

...或者您可以像其他人一样忽略它...

于 2009-04-20T20:25:12.033 回答
7

您可以使用一些 JavaScript 方法,如下所示

  1. self.location="http://www.example.com/index.php";

  2. window.location.href="http://www.example.com/index.php";

  3. document.location.href = 'http://www.example.com/index.php';

  4. window.location.replace("http://www.example.com/index.php");

于 2015-03-12T09:42:18.447 回答
7

要在 php 中重定向,请使用:

<?php header('Location: URL'); exit; ?>

于 2021-01-07T16:01:09.370 回答
7

是的,您可以使用header()函数,

header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();

最好的做法是在函数之后立即调用exit()header()函数以避免下面的代码执行。

根据文档,header()必须在发送任何实际输出之前调用。

于 2017-11-28T01:04:54.573 回答
6

就像这里的其他人所说,发送位置标头:

header( "Location: http://www.mywebsite.com/otherpage.php" );

但是您需要在将任何其他输出发送到浏览器之前执行此操作。

另外,如果您要使用它来阻止未经身份验证的用户访问某些页面,就像您提到的那样,请记住,某些用户代理会忽略这一点并继续在当前页面上,所以您需要死( ) 发送后。

于 2009-04-20T14:23:17.973 回答
6

以下是我的想法:

恕我直言,重定向传入请求的最佳方法是使用位置标头,即

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

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

尽管这是实现最初要求的快速而肮脏的方法,但最终会成为 SEO 灾难,因为这种重定向总是被解释为 301 / 302 重定向,因此搜索引擎将始终看到您的索引页面作为重定向页面,而不是登录页面/主页。

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

于 2017-01-28T14:48:31.727 回答
5

使用 PHP 重定向的最佳方法是以下代码...

 header("Location: /index.php");

确保之后没有代码可以工作

header("Location: /index.php");

所有代码必须在上述行之前执行。

认为,

情况1:

echo "I am a web developer";
header("Location: /index.php");

它将正确重定向到该位置(index.php)。

案例二:

return $something;
header("Location: /index.php");

上面的代码不会重定向到该位置(index.php)。

于 2017-04-09T08:37:42.293 回答
5

您可以尝试使用

header('Location:'.$your_url)

更多信息可以参考php官方文档

于 2021-06-14T10:14:22.050 回答
4

使用标头功能进行路由

<?php
     header('Location: B.php');
     exit();
?>

假设我们想从A.php文件路由到B.php而我们必须借助<button>or <a>。让我们看一个例子

<?php
if(isset($_GET['go_to_page_b'])) {
    header('Location: B.php');
    exit();

}
?>

<p>I am page A</p>
<button name='go_to_page_b'>Page B</button>

B.php

<p> I am Page B</p>
于 2020-03-15T07:52:05.200 回答
4

1.使用header,内置PHP函数

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>";
   ?>
于 2018-08-03T13:26:57.703 回答
3

我们可以通过两种方式做到这一点:

  1. 当用户访问https://bskud.com/PINCODE/BIHAR/index.php然后重定向到https://bskud.com/PINCODE/BIHAR.php

    通过以下 PHP 代码

    <?php
        header("Location: https://bskud.com/PINCODE/BIHAR.php");
        exit;
    ?>
    

    将上述代码保存在https://bskud.com/PINCODE/BIHAR/index.php

  2. 当任何条件为真时,重定向到另一个页面:

    <?php
        $myVar = "bskud";
        if ($myVar == "bskud") {
    ?>
    
    <script> window.location.href="https://bskud.com";  </script>
    
    <?php
        }
        else {
            echo "<b>Check the website name again</b>";
        }
    ?>
    
于 2018-01-04T07:30:17.283 回答
2
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

于 2022-01-03T16:34:17.957 回答
2

我喜欢数秒后的那种重定向

<?php

header("Refresh: 3;url=https://theweek.com.br/índex.php");
于 2020-01-13T05:21:08.670 回答
2

利用:

<?php
    $url = "targetpage"
    function redirect$url(){
        if (headers_sent()) == false{
            echo '<script>window.location.href="' . $url . '";</script>';
        }
    }
?>
于 2017-11-20T19:10:01.680 回答
2

有多种方法可以做到这一点,但如果您愿意php,我建议您使用该header()功能。

基本上

$your_target_url = “www.example.com/index.php”;
header(“Location : $your_target_url”);
exit();

如果你想让它更上一层楼,最好在函数中使用它。这样,您就可以在其中添加身份验证和其他检查元素。

让我们通过检查用户的级别来尝试。

因此,假设您已将用户的权限级别存储在名为u_auth.

在里面function.php

<?php
    function authRedirect($get_auth_level,
                          $required_level,
                          $if_fail_link = “www.example.com/index.php”){
        if ($get_auth_level != $required_level){
            header(location : $if_fail_link);
            return false;
            exit();
        }
        else{
            return true;
        }
     }

     . . .

然后,您将为要验证的每个页面调用该函数。

喜欢在page.php或任何其他页面。

<?php

    // page.php

    require “function.php”

    // Redirects to www.example.com/index.php if the
    // user isn’t authentication level 5
    authRedirect($_SESSION[‘u_auth’], 5);

    // Redirects to www.example.com/index.php if the
    // user isn’t authentication level 4
    authRedirect($_SESSION[‘u_auth’], 4);

    // Redirects to www.someotherplace.com/somepage.php if the
    // user isn’t authentication level 2
    authRedirect($_SESSION[‘u_auth’], 2, “www.someotherplace.com/somepage.php”);

    . . .

参考;

于 2018-01-28T22:17:07.200 回答
1

试试这个

 $url = $_SERVER['HTTP_REFERER'];
 redirect($url);
于 2020-01-09T13:21:27.177 回答
0

如果您在 Apache 上运行,您还可以使用 .htaccess 进行重定向。

Redirect 301 / http://new-site.com/
于 2017-10-13T10:56:05.223 回答
0

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

ob_start();
header("Location: " . $website);
ob_end_flush();
于 2016-11-15T10:15:19.373 回答