【问题标题】:While loop combined with header() in PHPPHP 中的 While 循环与 header() 结合使用
【发布时间】:2010-11-09 22:58:58
【问题描述】:

我已经编写了一个脚本来对一些点进行地理编码,这些点的结构基本上是这样的:

//get an unupdated record
$arr_record;
while(count($arr_record) > 0)
{
//strings are derived from $arr_record
geocode($string1);
geocode($string2);
geocode($string3);
array_pop($arr_record);
}

function geocode($string) {
   //if successful
      update($coords)
}

function update($coords) {
   //update the database
   header('Location:http://localhost/thisfile.php')
}

问题在于,即使地理编码成功并更新了数据库,并且重新发送了标头,脚本仍会返回到 while 循环,而无需重新加载页面并重新开始新记录。

这是 PHP 的正常行为吗?我该如何避免它出现这样的行为?

【问题讨论】:

  • 我有点疑惑,为什么要重新加载页面?
  • 为了保持一致,考虑在 : -- Location: http... -- 之后放置一个空格 -- 并确保 exit();
  • 重新加载页面的原因是我无法将 php 作为 CGI 运行,如果我告诉一个页面迭代太多次它就会超时。重新加载页面使我能够在没有任何超时的情况下进行尽可能多的迭代。

标签: php header geocoding while-loop


【解决方案1】:

在 header() 之后使用 die();终止脚本并输出。

【讨论】:

  • 脚本将输出空正文,但标题将有其他位置,因此浏览器会将用户重定向到该位置。
【解决方案2】:

如何避免它出现这样的行为?

将 exit() 放在 header() 之后。

【讨论】:

    【解决方案3】:

    另一种有效的方法是不直接在循环中发送标头。这是不正确的(我在 php.net 手册中找不到,但我记得之前在 phpusenet 中讨论过)。 它在不同的 php 版本中可能会出乎意料。 & 不同的 Apache 版本。安装。 php as cgi 也会出问题。

    您可以将其指定为以字符串形式返回,然后您可以稍后发送标头...

    function update($coords) {
           //update the database
    
           if(statement to understand update is ok){ 
           return 'Location:http://localhost/thisfile.php';
           } else {  
               return false;   
           }
        }
    
       if($updateresult=update($cords)!=false){ header($updateresult); }
    

    但如果我是你...我会尝试工作 ob_start() ob_get_contents() ob_end() 因为这些是控制将发送到浏览器的内容的绝佳方式。正常的 mimetypes 或标题...随便。这是同时处理标题和 html 输出的更好方法。

    ob_start();  /* output will be captured now */
      echo time();  /* echo test */
      ?>
        print something more...
      <?php  /* tag test */
    
     /* do some stuff here that makes output. */
    
    $content=ob_get_contents(); 
    ob_end_clean();
     /* now everything as output with echo, print or phptags. 
        are now stored into $content variable 
        then you can echo it to browser later 
     */
    
    echo "This text will be printed before the previous code";
    echo $content;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-26
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 1970-01-01
      • 2013-03-16
      相关资源
      最近更新 更多