PHP closing tags are the cause of 'Header already sent' errors?

Well in the latest version of Netbeans, I receive warnings for all the PHP closing tags ?> used at the end of the class files. Netbeans says that its a good practice not to use closing PHP delimiter at the end of the file, as it’s just a source of ‘Header already sent’ errors. Is this true? If so, why does PHP closing tag ?> cause ‘Header already sent’ errors?

If there is any whitespace after the closing tag, then that whitespace is considered content to send to the browser. And once you start sending content, then it’s too late to set any headers. When it happens, it’s hard to track down. And it happens often enough to be a nuisance. Leaving off the closing tag is an easy way to prevent this problem. And since there’s no drawbacks to doing so, it’s become a best practice, avocated by both the PHP-FIG and the [URL=“http://www.php.net/manual/en/language.basic-syntax.phptags.php”]PHP manual.

I see, thanks for the explanation. I dont normally get header already sent errors, although some users of my script do every now and then and I never manage to find a way to fix it. Guess this may be why.

Keep in mind, if you have any files that are a mixture of HTML and PHP, closing tags are required. They are only optional for files that are ONLY PHP.

Sure, thats not a problem for me as I never mix HTML with PHP. I find it a bad web programming practice, too bad so many people are still doing this. sigh

That is not completely correct. If there is a newline character after the closing tag, it will be consumed as part of the tag rather than being output. If there is any other character, or any further newlines then those will be output. In summary: ending a file with "?>
" will not output the newline character.

True. I’ll try to remember to include that qualification in the future.

I saw the same in the latest version of Netbeans. I simply disabled the warning in the settings. I find it elegant and logical to include the closing tag and I don’t know why this has become ‘bad practice’ - just because some people add unnecessary whitespace at the end of files? Netbeans should detect whitespace other than newline after the closing php tag and warn against it - not about the closing tag. When I open a tag it is logical to me to close it just like in XML, (X)HTML, etc. Just my personal point of view.

That’s not true - if the last thing in a file containing both HTML and PHP is PHP then the ?> at the end can still be omitted. It is only where HTML follows PHP that you need to close the PHP.

Maybe not bad practice per se, but that omitting the end tag has become better practice.

I agree. It feels like it violates our sense of strict syntax. I’ve had to simply push that aside and choose to be pragmatic. I found it interesting to think of the opening tag as if it were a shebang line, just like we might write #!/usr/bin/perl or #!/bin/sh at the top of other programming files.

Fair enough.