Search code examples
phphttp-status

how to control the http status code properly?


I met a strange thing when test the 400 error handling in CodeIgniter.

Message: Cannot modify header information - headers already sent by (output started at ...)

And the http status code is always 200, finally I found that there is a new line before <?php .... Then I checked the php doc, found this:

header() is used to send a raw HTTP header. See the » HTTP/1.1 specification for more information on HTTP headers.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

So how to set the http status code properly in php to make sure it is before any output? I am new to php programming. Thanks for you reply!


Solution

  • As others have said, you must send headers (i.e. use header()) before any other output.

    One thing that can often happen is that sometimes you include files that inadvertently have newlines in them, after the closing PHP tag. e.g.

    <?php
    /*
     * This is a file of PHP code
     */
    
    
    /*
     * file ends here
     */
    ?>
    
    __________________________ (actual end of file)
    # unexpected newline above gets sent as output
    

    In order to reduce the chances of this, you can deliberately leave out the closing PHP tag. The file will be parsed as PHP until the end, so there's far less chance of spurious newlines or spaces being sent from an included file.

    Depending on your editor, you can also set it to show whitespace (carriage returns, spaces, tabs), which can help when trying to eliminate unexpected output from your scripts (Eclipse and Notepad++ can both do it, for example).