open core »

PHP files - Closing the PHP tag or not?

Allot of people think that a PHP file without a closing tag, is not also strange but wrong and won't compile. But that's far from the truth. In fact, even Zend (the company behind the PHP language) forbids its use in the Zend Framework.

Here's an example:

function foobar ($foo) {
    echo $foo;
    return 0;

Most programmers in a file like this, would put a ?> in the end. It's ok. But in PHP-only files, it's not recommended.

How come this is a good practice? Well, first of all, the PHP interpreter won't complain about a missing closing tag. And second, the most important, is that leaving the file without a closing tag will avoid accidental injection of trailing whitespace into the response.

Quoting Zend manual:

The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include() or require(), so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.

Off course that there are people radically disagreeing with this. They point out that leaving the PHP tag open is programming lazyness (although I don't see how anyone can be lazy about writing two characters) and they also state that it's fear, it's an "easy and safe solution". Well the "easy" part it makes some sense, but the "safe" one?! Oh, ok... let's just fire all the security conscious programmers! Who needs security? Security is bad. Not. PHP already has a very bad reputation because of his kind of attitude.

I'm sure there are better arguments against this, but my opinion is to leave it open, don't close the tag, it can bring unnecessary problems. It won't harm your PHP code and won't make you lose hours trying to debug some invisible white spaces.