how to control the http status code properly?

197 Views Asked by At

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!

3

There are 3 best solutions below

0
On BEST ANSWER

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).

0
On

So how to set the http status code properly in php to make sure it is before any output?

You call header() before you do anything that creates output (including putting whitespace characters outside <?php sections).

3
On

Please your header() function before anything is ever returned to the visitor.

If you are unable to determine where something is being returned before calling header(), add an ob_start() function in the beginning of the PHP script.

Though it will work, I still suggest you to clean up your code and to not let data be outputted before it should. It is a better practice to always know what is happening within your own code and not to fall back to patch solutions.