Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the arguments IN FAVOR of PHP closing tags for PHP only files?

Tags:

php

The Zend Framework coding standard mentions the following:

For files that contain only PHP code, the closing tag ("?>") is never permitted. It is not required by PHP, and omitting it prevents the accidental injection of trailing whitespace into the response.
  • Zend Framework coding standard: file formatting

However I do remember hearing about an issue (with tooling or including maybe?) where files needed to have closing tag.

Does anyone know of any issues (other than the developer issue of wanting symmetry) where you would need to have closing tags or are they generally a bad idea?

like image 230
Boy Baukema Avatar asked Oct 25 '08 14:10

Boy Baukema


People also ask

What is the closing tag for PHP?

The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.

What is the correct PHP opening and closing tags?

php and ?>. These are called PHP's opening and closing tags. Statements witihn these two are interpreted by the parser. PHP script within these tags can be embedded in HTML document, so that embedded code is executed on server, leaving rest of the document to be processed by client browser's HTML parser.

Why is it considered a best practice to avoid using a PHP closing tag ?> In PHP files that contain only PHP code?

It is recommended that a closing PHP tag shall be omitted in a file containing only PHP code so that occurrences of accidental whitespace or new lines being added after the PHP closing tag, which may start output buffering causing uncalled for effects can be avoided.

Is it necessary to close PHP tag?

For files that contain only PHP code, the closing tag ( ?> ) is never permitted. It is not required by PHP, and omitting it prevents the accidental injection of trailing white space into the response.


2 Answers

Removing the closing tags when you can is probably a best practice really. The reason for that is because if you have any character (even whitespace) outside of the ?> in a php file it can stop thing such as headers to stop working if the character gets sent to the browser before the header gets set.

like image 175
James Murray Avatar answered Sep 19 '22 17:09

James Murray


If you use closing PHP tags then you can easily find files that have been accidentally truncated (e.g. haven't been uploaded completely).
However such problem should be fixed by making filesystem and transfers reliable rather than adding PHP "canary" tags :)

Another possible reason is that PEAR coding standards require it. They require it, because they require it and you're not allowed to question PEAR coding standards.

like image 21
Kornel Avatar answered Sep 22 '22 17:09

Kornel