0

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!

Community
  • 1
  • 1
Fourj
  • 1,817
  • 1
  • 18
  • 34

3 Answers3

2

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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

Daren Chandisingh
  • 2,157
  • 1
  • 13
  • 17
0

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.

  • -1 for using `ob_start()` as a band-aid, but +1 for acknowledging that using `ob_start()` as a band-aid is a bad idea. โ€“  Nov 27 '11 at 18:35
  • @Phoenix, that is why I said that I recommend the user to clean up the code if possible, instead of using the ob_start() method. Anyway if he is forced to solve the issue quickly and have no time or cannot clean up the code, ob_start() will work. I hope you will remove your down-vote now. โ€“  Nov 27 '11 at 18:41
  • There was no downvote; the virtual -1 was canceled out by the virtual +1. โ€“  Nov 27 '11 at 18:46