Closing a PHP tag - when is it necessary?

He recommended that you should not put a closing PHP tag at the end of the file to avoid all kinds of failed errors. But are there any circumstances where you need to close the PHP tag?

+4
source share
6 answers

A closing tag is required if you want to switch from a block of PHP code to plain text output.

Here is an example:

<?php // PHP code block ?> <!-- plain text output and not processed by PHP --> </body> 
+17
source

BTW, if you want to know what error you are preventing by skipping the closing tag. Because Zend's explanation is not included in the details.

This is not required by PHP, and its exclusion prevents accidental injection of a trailing space in the response.

This means that if you want to use header () to redirect a person to another place or change the HTTP header in some way ... then you will not be able to get an error if some file ends like this.

 } ?> //space here 

Because then this space will be displayed on the site as content, and then you will not be able to change the headers.

+9
source

This is my personal rule:

  • File with php code only: Never end a tag
  • File with php mixed with something else (Ie HTML): Always end tag
+5
source

This is only necessary when you want to output non-php code after your php block.

+3
source

If you are not using PHP in the script :-)

+1
source

As a rule, I always add a closing tag, because this is the only time during the day that my question mark gets an exercise with a finger. This bad question mark doesn't get love in PHP; -)

But seriously, adding a closing tag when not needed can lead to really confusing errors. Because of this, I pulled out my hair all day. The problem usually is that after the closing tag there are spaces that you cannot easily see, but they are interpreted as part of the response body. This is bad news if you include this file in another script that wants to send a custom header later. You cannot send header information after the script starts sending the response body, so these small invisible spaces lead to a script error.

+1
source