【问题标题】:How to redirect with header location in php when using ob_start?使用ob_start时如何在php中使用标头位置重定向?
【发布时间】:2012-08-03 02:52:51
【问题描述】:
<?php

ob_start();

echo "<body><p>Hello "

if ($condition) {
   header( "Location: http://www.google.com/" );
   exit;
}

echo " World!</p></body>";
ob_end_flush();

?>

$condition 为真时,我明白了:

<body>Hello

我想要的是当$condition 为真然后去谷歌!!!

我不知道发生了什么,你能解释一下或者给我一个解决方案吗!?

谢谢。

【问题讨论】:

  • IMO,ob_start() 可以去掉
  • 我无法删除 ob_start() 因为我需要在写入客户端之前处理输出。

标签: php header location ob-start


【解决方案1】:

只需在标头调用之前添加ob_end_clean();

【讨论】:

    【解决方案2】:

    一切都应该正常,只需在 echo "&lt;body&gt;&lt;p&gt;Hello" 之后添加一个 ; 就可以了。..

    【讨论】:

      【解决方案3】:

      如果我是你,我会先开始可能出错的地方,然后再进行处理。

      一个例子

      $exit_condition_1 = some_value1;
      $exit_condition_2 = some_value2;
      
      if($exit_condition_1 == false){
      
           //Redirect
           //Exit
      
      }
      
      if(!$exit_condition_2){
      
           //Redirect
           //Exit
      
      }
      
      
      //start the buffer ob_start()
      
      //show some HTML
      
      //flash the buffer ob_end_clean()
      
      there is no point of starting the buffer then if something goes wrong close it and redirect. Just do value testing at the begining then process the request.
      
      An example: lets say that you want to view a product's info and you have a function that will do that
      
      
      function view_product($product_id){
      
         if(!$product = getProductById($product_id)){
      
              //product does not exist, redirect
         }
      
      
         if(the user does not have enough access rights){
      
           //show a message maybe 
           //redirect
         }
      
      
         //everything is alright then show the product info
      
      }
      

      【讨论】:

        【解决方案4】:

        为了解决函数使用 ob_start() 并且之后出现 header("Location: http://www.example.com"); 但错误“已经发送...”的类似情况,我将 header(... 调用替换为

        echo "<script> window.location.href = 'https://www.example.com' </script>"
        

        它在那种特殊情况下有效(无论如何,只需要一个页面重定向)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-11-06
          • 2022-01-17
          • 2020-03-26
          • 2017-02-11
          • 1970-01-01
          • 2015-11-01
          • 2013-08-22
          相关资源
          最近更新 更多