Omit the PHP Closing Tag

Published: January 27th, 2009 by:

This is just a simple tip that presents a simple proposition - stop closing your PHP tags. Why? I will explain in this article. Keep in mind that this idea / standard only applies to PHP files that are only for PHP - no HTML.


PHP developers frequently encounter the problem with sending headers and cookies after output has been sent to the browser, but that problem can also happen with unintentional output. If whitespace gets inserted after the end of a PHP code block, that can produce unintentional output when that PHP script is included.

Solution: If that last closing tab is removed, PHP will not output that whitespace. What I have started to do is comment the closing tag out. This will make PHP process the whitespace instead of sending it to the browser, and since the tag is still there, you know it’s the end of the file in case it gets truncated for whatever reason.

If this sounds like an unusual solution, the Zend Framework makes this a requirement in their reference guide. Although they lost a bit of credit with me when I saw they require spaces over tabs. :)


One Response to “Omit the PHP Closing Tag”

  • aftersyok

    i was wondering why some new programmers in my company do not use php closing tag. these guys are better php programmer than me eventhough i’m 5 years older.
    however, while i have been coding PHP almost as long as you are, somehow I have never encounter even once the unintentional space-after-php-closing-tag output problem. guess i’ve been so lucky through these years that i never noticed such problem. or it could have been something with me using the @ob_start() function in each starting php files i use.
    anyway thanks for the great, simple, and helpful tips.

     

Leave a Reply





Wordpress doesn't like it when you post PHP code. Go save your code at pastebin, and post the link here.

About the Author

Andrew has been coding PHP applications since 2006, and has plenty of experience with PHP, MySQL, and Apache. He prefers Ubuntu Linux on his desktop and has plenty of experience at managing CentOS web servers. He is the owner of Wells IT Solutions LLC, and develops PHP applications full time for anyone that needs it as well as does desktop computer support locally in the local area. He spends most of his free time exploring new programming concepts and posting on The Webmaster Forums.