PHP Closing Tags Considered Harmful
Posted in PHP and Programming on Monday, the 16th of February, 2009.
Tagged: php
It may be obvious to some, but this is a mistake I still see being made a lot, and I think it's high time we got over it.
Stop using PHP closing tags. It really is that simple, and here's why.
Before I elaborate, let's illustrate what I mean. In short, this is indubitably bad:
<?php echo 'Hello World!'; ?>
Whilst this is good:
<?php echo 'Hello World!';
Of course, if you're embedding HTML in PHP, or vice versa, you'll need to use closing tags to demarcate the two languages. But given a file containing only PHP code, the closing tag is completely superfluous.
Worse, the closing tag is potentially harmful, since any whitespace, accidental or otherwise, after the tag will be sent to the browser as output, with potentially catastrophic effects:
- Any output, even that tiny bit of whitespace, being sent to the browser will cause PHP to send the HTTP response headers. This means that if, later on in your script, you wish to specify an HTTP header - such as a redirect - or drop a cookie, this will fail. Instead you'll generate the "Cannot modify header information - headers already sent" warning message, with which every PHP developer will be more than familiar
- If your output is in a fragile binary format, such as an image or SWF file, spurious whitespace has the potential to corrupt the file
- If you're outputting markup, leading newlines will push your XML prolog or Doctype Declaration off the top line of the output, thus rendering your markup invalid. I've had first-hand experience of this issue preventing sites from displaying at all on some mobile devices, which tend to be a bit more temperamental than full Web browsers when it comes to parsing markup
In any of these cases, tracking down an errant fragment of whitespace in a large codebase will be more pain than you really want. That's why omitting the closing tag is part of the Zend Framework coding standards among others.
So there you go. The solution is simple: stop using PHP closing tags.
Posted by Peter McDonald on Tuesday, the 24th of November, 2009.
Just recently started omitting the closing tag myself.
If you code carefully I see no reason not to include it but you are indeed correct it can stop a lot of headaches later.