首页 文章

如何在PHP中进行重定向?

提问于
浏览
1048

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

假设用户转到 www.example.com/page.php 并且我想将它们重定向到 www.example.com/index.php ,如何在不使用元刷新的情况下这样做?可能?

这甚至可以保护我的网页免受未经授权的用户

28 回答

  • 17

    如果你在Apache上运行,你也可以使用.htaccess进行重定向 .

    Redirect 301 / http://new-site.com/
    
  • 2
    header("Location: /index.php");
    exit(0);
    
  • 7

    您可以尝试使用php标头功能进行重定向 . 您将需要设置输出缓冲区,以便浏览器不会向屏幕发出重定向警告 .

    ob_start();
    header("Location: ".$website);
    ob_end_flush();
    
  • 1488
    <?php
    $url = "targetpage"
    Function redirect$url(){
       If (headers_sent()) == false{
          Echo '<script>window.location.href="' . $url . '";</script>';
    }}
    ?>
    
  • 91

    其中许多答案是正确的,但他们假设您有一个绝对URL,可能不是这种情况 . 如果你想使用 relative 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
    
  • 8

    你可以使用下面的一些java脚本方法

    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");
    
  • 1

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

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

    确保之后没有代码可用

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

    所有代码必须在上一行之前执行 .

    假设,

    Case 1:

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

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

    Case 2:

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

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

    希望很明显 .

  • 60

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

    <?php
    header("location:./");//redirect to index file
    header("location:index.php");//redirect to index file
    header("location:example.php");
    ?>
    
  • 10
    function Redirect($url, $permanent = false)
    {
        if (headers_sent() === false)
        {
            header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
        }
    
        exit();
    }
    
    Redirect('http://www.google.com/', false);
    

    别忘了死()/退出()!

  • 6

    我再次这样做,因为同时我在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重定向代码( 301302303307 )的问题,因为我在之前的回答的评论中已经解决过,这里是描述:

    • 301 - 永久移动

    • 302 - 发现

    • 303 - 见其他

    • 307 - 临时重定向(HTTP / 1.1)

  • 18

    1.使用带有exit()的头功能

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

    但是如果你使用 Headers 函数,那么有时候你会得到 "warning like header already send" 来解决在发送 Headers 之前不回显或打印的问题,或者你可以在 Headers 函数之后简单地使用 die()exit() .

    2.没有 Headers

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

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

    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
    ?>
    
  • 23
    <?php header('Location: another-php-file.php'); exit(); ?>
    

    或者如果您已经打开了php标签,请使用:

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

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

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

    确保包含 exit()include die()

  • 6

    是的,你可以使用header()功能,

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

    并且最佳做法是在 header() 函数之后立即调用exit()函数以避免代码执行下面 .

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

  • 12
    <?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.
    ?>
    
  • 1

    回答这个问题可能为时已晚 . 不过,这是我的想法:

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

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

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

    虽然这是一种快速而肮脏的方式来实现最初的问题,但它最终会变成SEO灾难,因为这种重新指向总是被解释为301/302重定向,因此搜索引擎将始终将您的索引页面视为重定向页面,而不是登录页面/主页面 . 因此它会影响网站的SEO设置 .

  • 7

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

  • 5

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

    <?php
    
    session_start();
    
    if ( !isset( $_SESSION["valid_user"]) )
    {
        header("location:../");
       die();
    }
    
    // Page goes here
    ?>
    

    http://php.net/manual/en/reserved.variables.session.php .

    最近,我得到了网络攻击并决定,我需要知道用户尝试访问管理面板或保留部分Web应用程序 .

    所以,我在文本文件中添加了日志访问IP和用户会话,因为我不想打扰我的数据库 .

  • 5

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

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

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

    Relative/Absolute Path

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

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

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

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

    HTTP Headers

    根据HTTP协议,HTTP头必须发送 before 任何类型的内容 . 这意味着在 Headers 之前不应该发送任何字符 - 甚至不是空白空间!

    Temporary/Permanent Redirections

    默认情况下,上面显示的重定向类型是临时的 . 这意味着搜索引擎(例如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中输入第一个网址,系统会自动将您重定向到第二个重定向链接 .

    Interpretation of PHP Code

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

    <? 
    header('Status: 301 Moved Permanently', false, 301); 
    header('Location: address'); 
    exit(); 
    ?>
    
  • 0

    我们可以用两种方式做

    通过下面的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 Website Name Again</b>"; } ?>
    

    `

  • 4

    使用echo从PHP输出JavaScript,这将完成工作 .

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

    你不能在PHP中真正做到这一点,除非你缓冲页面输出,然后检查重定向条件 . 这可能太麻烦了 . 请记住, Headers 是从页面发送的第一件事 . 大多数重定向通常在页面后面需要 . 为此,您必须缓冲页面的所有输出并稍后检查重定向条件 . 此时,您可以重定向页面用户 Headers ()或只是回显缓冲输出 .

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

    What is output buffering?

  • 88

    使用header() function发送HTTP Location header

    header('Location: '.$newURL);
    

    与某些人认为相反, die() 与重定向无关 . 如果要重定向 instead 正常执行,请使用 only .

    使用example.php:

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

    结果或3次执行:

    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
    

    恢复 - 强制性 die() / exit() 是一些都市传奇,与实际PHP无关 . 与客户端"respecting" Location: 标头无关 . 无论使用何种客户端,发送标头都不会停止PHP执行 .

  • 1

    你可以在php中更新 Headers :header

  • 1

    像其他人说的那样,发送位置 Headers :

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

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

    此外,如果你打算使用它来阻止某些页面中未经过身份验证的用户,就像你提到的那样,请记住一些用户代理will ignore this然后继续在当前页面上,所以你需要在之后死掉()你发送它 .

  • 98

    在语义网的前夕,正确性需要考虑 . 不幸的是,PHP的"Location" -header仍然使用HTTP 302 -redirect代码,严格来说,它不是重定向的最佳代码 . 它应该使用的那个是303 .

    W3C非常友好mention 303-header与"many pre-HTTP/1.1 user agents,"不兼容,这相当于当前使用的浏览器 . 因此,302是遗物,不应该使用 .

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

  • 13

    1. Using header in-build php function

    a)没有参数的简单重定向

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

    b)使用GET参数重定向

    <?php
    
          $id = 2;
    
          header("Location: index.php?id=$id&msg=succesfully redirect");
    
      ?>
    

    2. Redirect with javascript in php

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

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

    1.基本答案

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

    header('Location: '.$newURL);
    

    2.重要细节

    die()exit()

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

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

    Absolute or relative URL

    自2014年6月起,可以使用绝对和相对URL . 请参阅RFC 7231,它已替换旧的RFC 2616,其中只允许使用绝对URL .

    Status Codes

    PHP的"Location" -header仍然使用HTTP 302 -redirect代码,但这不是您应该使用的代码 . 您应该考虑301(永久重定向)或303(其他) .

    注意:W3C mentions 303-header与“许多pre-HTTP / 1.1用户代理”不兼容 . 目前使用的浏览器都是HTTP / 1.1用户代理 . 对于蜘蛛和机器人等许多其他用户代理来说并非如此 .

    3.文档

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

    4.替代品

    您可以使用 http_redirect($url); 的替代方法,该方法需要安装PECL package pecl .

    5.辅助函数

    此功能不包含303状态代码:

    function Redirect($url, $permanent = false)
    {
        header('Location: ' . $url, true, $permanent ? 301 : 302);
    
        exit();
    }
    
    Redirect('http://example.com/', false);
    

    这更灵活:

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

    6.解决方法

    如提到 header() 重定向仅在写出任何内容之前工作 . 如果invoked inmidst HTML输出,它们通常会失败 . 然后你可能会使用HTML Headers 解决方法(不是很专业!),如:

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

    或者甚至是JavaScript重定向 .

    window.location.replace("http://example.com/");
    
  • 3

    有多种方法可以做到这一点,但如果您更喜欢 php ,我建议使用 header() 函数 .

    Basically

    $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”
    
    authRedirect($_SESSION[‘u_auth’], 5);  // redirects to www.example.com/index.php if the user isn’t auth level 5
    authRedirect($_SESSION[‘u_auth’], 4);  // redirects to www.example.com/index.php if the user isn’t auth level 4
    authRedirect($_SESSION[‘u_auth’], 2, “www.someotherplace.com/somepage.php”);  // redirects to www.someotherplace.com/somepage.php if the user isn’t auth level 2
    
    
    . . .
    

    我希望你能找到一些有用的内容

    参考;

  • 6

    大多数答案都忘记了重要的一步!

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

    离开那个重要的第二行可能会看到你最终The Daily WTF . 问题是浏览器不必尊重页面返回的 Headers ,因此如果忽略 Headers ,页面的其余部分将在没有重定向的情况下执行 .

相关问题