Graviton
Graviton

Reputation: 83264

PHP tag closing-- when is needed?

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?

Upvotes: 5

Views: 910

Answers (6)

Svish
Svish

Reputation: 158151

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

Upvotes: 5

Kyle Simek
Kyle Simek

Reputation: 9636

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.

Upvotes: 1

Ólafur Waage
Ólafur Waage

Reputation: 70001

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.

Upvotes: 9

Chathuranga Chandrasekara
Chathuranga Chandrasekara

Reputation: 20936

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

Upvotes: 1

alexn
alexn

Reputation: 58992

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

Upvotes: 3

Gumbo
Gumbo

Reputation: 655469

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>

Upvotes: 16

Related Questions