Solve the PHP "headersalreadysent" error

Source: Internet
Author: User
Solve the PHPheadersalreadysent error this article is the answer to a question on stackoverflow. The answer focuses on the ideas of other answers and summarizes them, in the future, if you encounter a "headers already sent" error, you can directly troubleshoot it one by one, or simply avoid such problems in code and design.

No output before sending the header

The method for sending or modifying HTTP header information must be called before any output is output. Otherwise, an error occurs:

Warning: CannotModifyHeader information-headers already sent (OutputStarted at script: line)

These methods can be used to modify the HTTP header information:

  • Header/header_remove
  • Session_start/session_regenerate_id
  • Setcookie/setrawcookie

Output can be:

  • Unintentional:
    • Space after
    • BOM UTF-8
  • Intentionally:
    • Print, echo, and other methods that can generate output
    • In Block
Why is this error?

To understand why HTTP headers must be sent before output, we need to understand the next typical HTTP response. The PHP script is mainly used to generate HTML, but it also sends a series of HTTP/CGI header information to the web server:

HTTP/1.1 200 OKPowered-By: PHP/5.3.7Vary: Accept-EncodingContent-Type: text/html; charset=utf-8PHP page output pageContent 

Some more output follows...

and

The page or output is always followed by the header information. PHP must first send the header information to the web server, and it can only be sent once. after that, it can no longer modify the header information.

When PHP receives the output for the first time (print, echo,) It clears all the collected header information. After that, it can output all the content to be output, but it is impossible to send the HTTP header information again.

How can we find out where the output is generated in advance?

The header () contains all information related to the problem:

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

In the preceding warning, line 100 points to the number of lines of scripts that failed to call header.

Output started in parentheses is more important. It indicates the source of the output before header. In this example, it is the 52nd line of auth. php. this is where you are looking for premature output.

Typical reasons include:

  1. Print,Echo

    Intentional print and echo statement output will interrupt the chance of output HTTP header information. Application streams must be reorganized to avoid such behavior. Functions and templates can be used to reorganize the application streams, so that header () calls are performed before the information is written.

    Output methods include:

    • Print, echo, printf, vprintf
    • Trigger_error, ob_flush, ob_end_flush, var_dump, print_r
    • Readfile, passthru, flush, imagepng, imagejpeg

    And other user-defined methods.

  2. Original HTML

    HTML blocks that are not parsed in a PHP file are also output. All the conditions in the script that may trigger the request header () must be in anyBlock pre-declaration.

  3. If the warning points to1The output of the row is likely to point

     
              

It may also appear in the attached script or script block:

?>
      

PHP indeed occupies a line break after the tag is closed, but it does not insert line breaks, tabs, or spaces in the blank space (that is, this is our own cause ).

  1. BOM UTF-8

    Line breaks or spaces may cause problems, but invisible character sequences are also acceptable. The most famous one is that most text editors do not displayBOM UTF-8. It is optional or even redundant in UTF-8-encoded documents and is labeled as the byte sequence of ef bb bf. However, PHP must treat it as the original output. It may be output with symbols such as Latin-1 (if the client interprets this document) or other such "invalid outputs ".

    You may not be aware of this type of files in a graphical editor or JAVA-based IDE.BOM UTF-8. They do notBOM UTF-8Visualization (subject to Unicode standards ). However, most Program editors and console editors will handle the following:

    In this way, you can easily discover problems early. Other editors can correct this problem after setting certain options (Notepad ++ on Windows can identify and correct BOM problems ), another way to find BOM is to use the hexadecimal editor. Most of the * nix systems provide hexdump. if not, other graphical variants can also be used to simplify the process of auditing these problems:

    A simple correction method is to set the text editorSave files with UTF-8 (no BOM)(Save files as UTF-8 (no BOM)) Or other similar settings.

    Amendment

    There are many automated tools to detect and modify text files (sed/awk or recode ). PHP contains phptags. It can enable or disable the label and rewrite the growth label (

    phptags  --whitespace  *.php

Similarly, you can use this command in a directory or the entire project directory.

  1. ?> After blank

    If the error code is in the closed tag>? Before this line, this is>? Leading space or original text output. The PHP end tag does not terminate the execution script when the tag is closed. Any?> Subsequent text or space characters are output as page content.

    A common encouraged approach, especially for new users, is to avoid adding closed labels behind PHP files.?>. In this way, we can avoid a part of such problems.

  2. Error source prompt: "Unknown on line 0"

    If no specific error source is provided, this is a typical PHP extension or php. ini setting problem:

    • Occasionally gzip encoding settings or ob_gzhandler
    • It may also be that the module in the php. ini settings is loaded twice, which causes PHP to generate a startup/warning message.
  3. An error message is output due to a previous error.

    If the preceding PHP statement or expression causes the output due to warning or notice information, the output is also considered premature.

    In this case, you need to avoid errors, push the execution of these statements, or suppress the output of these information. you can use isset () for judgment, or use the inhibitor @, the premise is that they will not prevent subsequent debugging.

No error message output

If you disable the error_reporting or display_errors settings in php. ini, no warning is generated. However, the ignore error does not cause the problem to disappear, and the header information cannot be sent before the premature output.

So when the jump from header ("Location:...") fails silently, we recommend that you check warnings. Run the following two commands at the beginning of the script to re-enable the error report settings:

error_reporting(E_ALL);ini_set("display_errors", 1);

Or if other settings fail, set set_error_handler ("var_dump ");.

As for the jump header, you should follow the following style when executing the final code:

exit(header("Location: /finished.html"));

It is best to provide a method, especially when the header () fails to print the user information.

Work und: Output Buffer

The PHP output buffer method is a work und to alleviate this problem. It runs reliably, but you should never use it to replace your well-structured application structure and separate the output from the control logic. Its real purpose is to reduce the pressure on large data transmission to the server.

  1. Output_buffering is set in php. ini or. htaccess, or even in. user. ini of the latest FPM/FastCGI;
  2. Similarly, you can use ob_start () at the beginning of the script, but it is not so reliable:
    • Even if In the first script, spaces or BOM may also be output before this.
    • It can hide spaces in HTML output (put spaces in buffer), but as long as the application logic attempts to send binary content (such as the generated image ), the irrelevant output in the buffer will become a problem (so the ob_clean () method will become the work und for the next step ).
    • There is a buffer size limit, and it is easy to exceed in the default configuration, and this situation is not uncommon, it is not easy to track once it occurs.

Therefore, these two methods become unreliable, especially when you need to change the configuration of the development environment or production environment. This is why the output buffer is considered as a poor work und.

We recommend that you refer to the basic usage in the official manual and its advantages and disadvantages:

  • What is the output buffer?
  • Why use output buffering
  • Is it difficult to use the output buffer?
  • Example of correct use of output buffering to solve "header already sent"
But is it good on other servers?

If you have not received the warning message, the output_buffering settings in php. ini have changed. It is very likely that no configuration is set on the current/different servers.

Use headers_sent () to check

You can use headers_sent to check whether header information can be sent. This method can effectively check to output an error message or apply other logic.

Good work und:

  • HTML Tag

    If your application is difficult to solve this problem in terms of structure, a simple but unprofessional approach is

    Tab to jump to the web page. This can be achieved as follows:

        

    Or add a delay time.

        

  • JavaScript jump

    Another optional method is to use JavaScript to redirect a webpage:

    《script》 location.replace("target.html"); 《script》

This method is compared

The method is more compatible with HTML standards. it only depends on clients that can run JavaScript.

The two methods provide an acceptable rollback method when the HTTP header () call fails. The idealized processing method should be to combine redirection with other methods to provide user-friendly auxiliary information and provide a clickable link for subsequent operations.

Why are both setcookie () and session_start () affected?

Both setcookie () and session_start () need to send an HTTP header of set-cookie. This situation is similar to the previous output header (), so errors may also occur due to premature output of error information.

(Of course, they may also be affected because the client disables cookies, and the setting may be a proxy problem. Obviously, the session depends on the size of the remaining disk space or other settings in php. ini)

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.