且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

参考 - 这个错误在 PHP 中是什么意思?

更新时间:2023-01-24 12:54:11

警告:无法修改标头信息 - 标头已发送

当您的脚本尝试向客户端发送 HTTP 标头但之前已经有输出时会发生这种情况,这导致标头已经发送到客户端.

Warning: Cannot modify header information - headers already sent

Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.

这是一个 E_WARNING 和它不会停止脚本.

This is an E_WARNING and it will not stop the script.

一个典型的例子是这样的模板文件:

A typical example would be a template file like this:

<html>
    <?php session_start(); ?>
    <head><title>My Page</title>
</html>
...

session_start() 函数将尝试将带有会话 cookie 的标头发送到客户端.但是 PHP 在将 <html> 元素写入输出流时已经发送了标头.您必须将 session_start() 移到顶部.

The session_start() function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the <html> element to the output stream. You'd have to move the session_start() to the top.

您可以通过检查触发警告的代码之前行并检查其输出位置来解决此问题.将任何标头发送代码移到该代码之前.

You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.

一个经常被忽视的输出是 PHP 结束 ?> 之后的新行.当 ?> 是文件中的最后一项时,省略它被认为是一种标准做法.同样,此警告的另一个常见原因是开头的 <?php 前面有空格、行或不可见字符,从而导致 Web 服务器发送标头和空格/换行符当 PHP 开始解析时将无法提交任何 header.

An often overlooked output is new lines after PHP's closing ?>. It is considered a standard practice to omit ?> when it is the last thing in the file. Likewise, another common cause for this warning is when the opening <?php has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.

如果您的文件中有多个 <?php ... ?> 代码块,则它们之间不应有任何空格.(注意:如果你有自动构建的代码,你可能有多个块)

If your file has more than one <?php ... ?> code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)

还要确保您的代码中没有任何字节顺序标记,例如当脚本的编码是带有 BOM 的 UTF-8 时.

Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.

相关问题: