【问题标题】:PHP Page redirect problem - Cannot modify header information [duplicate]PHP页面重定向问题 - 无法修改标题信息[重复]
【发布时间】:2011-10-21 22:15:32
【问题描述】:

我有一个页面显示各种元素,即使它从数据库调用的 id 不存在或被删除(这会引发各种丑陋的错误以及搜索引擎继续列出不存在的页面)。

如果 $id 不存在,您能否修改下面显示的页面代码的第一部分以发送 404(或至少发送到具有 404 标头的 projecterror.php)?非常感谢!

<?php
include_once("includes/linkmysql.php");
$adda=$_GET['a']; 
$cont=$_GET['c']; 
$select="SELECT * FROM projects where id='$id'";
$qselect = mysql_query($select);
while ($row = mysql_fetch_array($qselect)) { 

以下修改由Matt Wilson 建议,作为原始评论的结果 Vivek Goel 导致有效条目正确显示页面,但不存在的页面在此修改后的代码下方显示错误:

<?php
include_once("includes/linkmysql.php");
$adda=$_GET['a']; 
$cont=$_GET['c']; 
$select="SELECT * FROM projects where id='$id'";
$qselect = mysql_query($select);
if( mysql_num_rows( $qselect ) === 0 )
{
   header("HTTP/1.1 301 Moved Permanently");
   header( 'Location: http://examplesite.domain/errorpage' ) ;
   exit;
}
while ($row = mysql_fetch_array($qselect)) { 

以上修改导致的错误:

Warning: Cannot modify header information - headers already sent by (output started at /home/website/public_html/header1.php:14) in /home/website/public_html/header1.php on line 22 
Warning: Cannot modify header information - headers already sent by (output started at /home/website/public_html/header1.php:14) in /home/website/public_html/header1.php on line 23 Lines 22 and 23 are the two header lines in your example above

第 22 行和第 23 行是下面的两个标题行:

header("HTTP/1.1 301 Moved Permanently");
header( 'Location: http://examplesite.domain/errorpage' ) ;

【问题讨论】:

    标签: php redirect error-handling http-status-code-301


    【解决方案1】:

    在发送任何要查看的内容(浏览器中的文本)之前。 检查您的模型是否 id 有效。 如果 id 无效重定向到您的错误页面

    header("HTTP/1.1 301 Moved Permanently");
    header( 'Location: http://examplesite.domain/errorpage' ) ;
    

    【讨论】:

    • 您在放置标题之前发送了一些文本。这件事会在发送任何视图之前出现。 (浏览器的任何东西)
    • 文本在哪里?我无法解决这个问题...
    • 这是您的完整页面代码吗?或部分代码
    • project.php 是顶部有这个的主页(header1.php 是上面写的代码):&lt;?php $id=$_GET['id']; include_once("header1.php"); if (isset($_GET['id'])) $id=$_GET['id']; setprojectdetail($id,"views",projectattr($id,"views")+1); $det=projectdetail($id); date_default_timezone_set('CET'); ?&gt;
    • 我猜 include_once("header1.php");正在发送标头和数据。
    【解决方案2】:

    我为您提供了更简单的解决方案 - 很简单!只需在 php 源代码的最开始添加此命令:

    ob_start();
    

    这将开始缓冲输出,因此在 PHP 脚本结束(或直到您手动刷新缓冲区)之前,什么都不会真正输出 - 并且在此之前也不会发送任何标头! 所以你不需要重新组织你的代码,只需在你的代码的最开始添加这一行就可以了:-)

    【讨论】:

    • 伟大的工作 - 这完全符合预期,非常感谢!
    • 完美运行!。谢谢!
    【解决方案3】:

    在使用 php header() 重定向之前,不应向浏览器发送任何内容。如果标头已经发送,您可以尝试使用 javascript 重定向。

    if( mysql_num_rows( $qselect ) === 0 )
    {
       echo "<script type='text/javascript'>window.location.href='{http://examplesite.domain/errorpage}'</script>";
       exit;
    }
    

    但我不确定 javascript 重定向是否适合搜索引擎

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多