解决 PHP “headers already sent” 错误

发送 header 前不要有任何输出

发送或者修改 HTTP 头信息的方法必须在任何输出被输出之前被调用。否则调用将会出错:

Warning: Cannot modify header information - headers already sent by (output started at script:line)

这些方法可以修改(modify) HTTP 头信息:

输出(output)可以是:

  • 无意的:
    • <?php 之前或者 ?> 之后的空格
    • UTF-8 BOM
  • 有意的:
    • print ,echo 以及其他能产生输出的方法
    • 在 <?php 前原始的 <html> 区块

为什么这个错误会产生

HTTP/1.1 200 OK
Powered-By: PHP/5.3.7
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8

<html><head><title>PHP page output page</title></head>
<body><h1>Content</h1> <p>Some more output follows...</p>
and <a href="/"> <img src=internal-icon-delayed> </a>

页面或者输出总是紧跟在头信息后面。PHP 必须先把头信息发送给 web 服务器,并且它只能发送一次,在这之后就再也不能修改头信息了。

当 PHP 第一次接收到输出时(print ,echo,<html>) 它会清掉所有收集到的头信息。在此之后它能把输出所有想输出的内容,但是再想发送 HTTP 头信息就不可能了。

怎么找到到底是哪里提前产生了输出?

header() 头信息包含所有与问题产生相关的信息:

Warning: Cannot modify header information - headers already sent by (output started at /www/usr2345/htdocs/auth.php:52) in /www/usr2345/htdocs/index.php on line 100

在上面的警告中,line 100 指向调用 header() 失败的脚本行数。

圆括号里的 output started 这条信息更加重要。它指出了先于 header() 前的输出的源头。在这个例子中是 auth.php 的 第 52 行,这就是你要去找的过早的输出的地方。

本文参考:http://blog.jayxhj.com/2016/03/fix-headers-already-sent-error-in-php/

https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php

Leave a comment

您的电子邮箱地址不会被公开。 必填项已用 * 标注