PHP closing tag and tags with html

I had a problem recently with ‘headers already sent’ which was traced to white-space at the end of an included php file which because of the php.ini error level was displaying an error to browser and catching out the header() function.

In the past I’ve always put a trailing ?> tag in a php file to match the mandatory

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.

In my own more recent php5 coding I’ve tended not to include the closing tag. For the most recent developments I’ve removed it and replaced it by a comment //end directly below the last command line – just to signify this is the end of the file for the developers benefit. This will make PHP process the end of the php file and process the whitespace instead of sending it to the browser.

If this sounds like an unusual solution, the Zend Framework makes the absence of a closing tab a requirement in their reference guide: Zend Framework -

http://en.wikibooks.org/wiki/Programming:Complete_PHP/Escaping_from_HTML

Another bugbear of mine when looking at other code is escaped html within php code. Simple answer… DON’T. Raw HTML is interpreted faster, and php enclosed tags should be just for php code that requires interpreting. The code looks cleaner and more professional as well. For example:

if ($weekday >= 6) {
?>

Happy weekend. Why are you still at work?

} else {
?>

Today is work. Ugh.

}
?>

By the way never use short-tags and it’s better to turn this off in php.ini. It will be deprecated – probably in php5.3 and definately in php6.

Leave a Reply