tags:

views:

359

answers:

6

It's recommended that one should not put a PHP closing tag at the end of the file to avoid all sorts of untoward error. But is there any circumstances when PHP tag closing is needed?

+15  A: 

A closing tag is needed if you want to switch from the PHP code block to the plain text output.

Here’s an example:

<?php
    // PHP code block
?>
<!-- plain text output and not processed by PHP -->
</body>
Gumbo
Thanks, but beyond that?
Ngu Soon Hui
Beyond that? Never.
alexn
+2  A: 

It's only needed when you want to output non-php code after your php block.

alexn
+1  A: 

When you are not just using PHP in the script :-)

Chathuranga Chandrasekara
+5  A: 

BTW if you want to know what error you are preventing by skipping the closing tag. Since Zend's explanation doesn't go into detail.

It is not required by PHP, and omitting it prevents the accidental injection of trailing white space into the response.

This means that if you want to use header() to redirect some person to some other location or change the HTTP header in any way... then you can't and will get an error if some file ends like this.

}
?>
 //space here

Because then this space will be outputted to the site as content and then you can't modify the headers.

Ólafur Waage
A: 

As a general rule, I always add the closing tag, because it's the only time all day that my question-mark finger gets exercise. That poor question mark gets no love in PHP ;-)

But seriously, adding the closing tag when it's not required can actually lead to really confusing errors. I pulled my hair out all afternoon once because of this. The trouble is usually because there's spaces after the closing tag that you can't easily see, but they get interpreted as part of a response body. This is bad news if you're including this file inside another script that wants to send a custom header later on. You can't send header information after a script has started sending the response body, so these little invisible spaces result in the script failing.

redmoskito
Don't forget the ternary operator: $var = expr ? true-val : false-val;
James Socol
+2  A: 

This is my personal "rule":

  • File with only php code: Never end tag
  • File with php mixed with something else (I.e. HTML): Always end tag
Svish