Why would one omit the close tag?

2018-12-31 01:08发布

I keep reading it is poor practice to use the PHP close tag ?> at the end of the file. The header problem seems irrelevant in the following context (and this is the only good argument so far):

Modern versions of PHP set the output_buffering flag in php.ini If output buffering is enabled, you can set HTTP headers and cookies after outputting HTML because the returned code is not sent to the browser immediately.

Every good practice book and wiki starts with this 'rule' but nobody offers good reasons. Is there another good reason to skip the ending PHP tag?

14条回答
大哥的爱人
2楼-- · 2018-12-31 01:44

It's a newbie coding style recommendation, well-intentioned, and advised by the manual.

  • Eschewing ?> however solves just a trickle of the common headers already sent causes (raw output, BOM, notices, etc.) and their follow-up problems.

  • PHP actually contains some magic to eat up single linebreaks after the ?> closing token. Albeit that has historic issues, and leaves newcomers still susceptible to flaky editors and unawarely shuffling in other whitespace after ?>.

  • Stylistically some developers prefer to view <?php and ?> as SGML tags / XML processing instructions, implying the balance consistency of a trailing close token. (Which btw, is useful for dependency-conjoining class includes to supplant inefficient file-by-file autoloading.)

  • Somewhat uncommonly the opening <?php is characterized as PHPs shebang (and fully feasible per binfmt_misc), thereby validating the redundancy of a corresponding close tag.

  • There's an obvious advise discrepancy between classic PHP syntax guides mandating ?>\n and the more recent ones (PSR-2) agreeing on omission.
    (For the record: Zend Framework postulating one over the other does not imply its inherent superiority. It's a misconception that experts were drawn to / target audience of unwieldy APIs).

  • SCMs and modern IDEs provide builtin solutions mostly alleviating close tag caretaking.

Discouraging any use of the ?> close tag merely delays explaining basic PHP processing behaviour and language semantics to eschew infrequent issues. It is practical still for collaborative software development due to proficiency variations in participants.

Close tag variations

  • The regular ?> close tag is also known as T_CLOSE_TAG, or thus "close token".

  • It comprises a few more incarnations, because of PHPs magic newline eating:

    ?>\n (Unix linefeed)

    ?>\r (Carriage return, classic MACs)

    ?>\r\n (CR/LF, on DOS/Win)

    PHP doesn't support the Unicode combo linebreak NEL (U+0085) however.

    Early PHP versions had IIRC compile-ins limiting platform-agnosticism somewhat (FI even just used > as close marker), which is the likely historic origin of the close-tag-avoidance.

  • Often overlooked, but until PHP7 removes them, the regular <?php opening token can be validly paired with the rarely used </script> as odd closing token.

  • The "hard close tag" isn't even one -- just made that term up for analogy. Conceptionally and usage-wise __halt_compiler should however be recognized as close token.

    __HALT_COMPILER();
    ?>
    

    Which basically has the tokenizer discard any code or plain HTML sections thereafter. In particular PHAR stubs make use of that, or its redundant combination with ?> as depicted.

  • Likewise does a void return; infrequently substitute in include scripts, rendering any ?> with trailing whitespace noneffective.

  • Then there are all kinds of soft / faux close tag variations; lesser known and seldomly used, but usually per commented-out tokens:

    • Simple spacing // ? > to evade detection by PHPs tokenizer.

    • Or fancy Unicode substitutes // ﹖﹥ (U+FE56 SMALL QUESTION MARK, U+FE65 SMALL ANGLE BRACKET) which a regexp can grasp.

    Both mean nothing to PHP, but can have practical uses for PHP-unaware or semi-aware external toolkits. Again cat-joined scripts come to mind, with resulting // ? > <?php concatenations that inline-retain the former file sectioning.

So there are context-dependent but practical alternatives to an imperative close tag omission.

Manual babysitting of ?> close tags is not very contemporary either way. There always have been automation tools for that (even if just sed/awk or regex-oneliners). In particular:

phptags tag tidier

https://fossil.include-once.org/phptags/

Which could generally be used to --unclose php tags for third-party code, or rather just fix any (and all) actual whitespace/BOM issues:

  • phptags --warn --whitespace *.php

It also handles --long tag conversion etc. for runtime/configuration compatibility.

查看更多
美炸的是我
3楼-- · 2018-12-31 01:46

It's pretty useful not to let the closing ?> in.

The file stays valid to PHP (not a syntax error) and as @David Dorward said it allows to avoid having white space / break-line (anything that can send a header to the browser) after the ?>.

For example,

<?
    header("Content-type: image/png");
    $img = imagecreatetruecolor ( 10, 10);
    imagepng ( $img);
?>
[space here]
[break line here]

won't be valid.

But

<?
    header("Content-type: image/png");
    $img = imagecreatetruecolor ( 10, 10 );
    imagepng ( $img );

will.

For once, you must be lazy to be secure.

查看更多
宁负流年不负卿
4楼-- · 2018-12-31 01:46

"Is there another good reason (other than the header problem) to skip the ending php tag?"

You don't want to inadvertently output extraneous whitepace characters when generating binary output, CSV data, or other non-HTML output.

查看更多
宁负流年不负卿
5楼-- · 2018-12-31 01:47

While I can't remember any other reason, sending headers earlier than the normal course may have far reaching consequences. Below are just a few of them that happened to come to my mind at the moment:

  1. While current PHP releases may have output buffering on, the actual production servers you will be deploying your code on are far more important than any development or testing machines. And they do not always tend to follow latest PHP trends immediately.

  2. You may have headaches over inexplicable functionality loss. Say, you are implementing some kind payment gateway, and redirect user to a specific URL after successful confirmation by the payment processor. If some kind of PHP error, even a warning, or an excess line ending happens, the payment may remain unprocessed and the user may still seem unbilled. This is also one of the reasons why needless redirection is evil and if redirection is to be used, it must be used with caution.

  3. You may get "Page loading canceled" type of errors in Internet Explorer, even in the most recent versions. This is because an AJAX response/json include contains something that it shouldn't contain, because of the excess line endings in some PHP files, just as I've encountered a few days ago.

  4. If you have some file downloads in your app, they can break too, because of this. And you may not notice it, even after years, since the specific breaking habit of a download depends on the server, the browser, the type and content of the file (and possibly some other factors I don't want to bore you with).

  5. Finally, many PHP frameworks including Symfony, Zend and Laravel (there is no mention of this in the coding guidelines but it follows the suit) and the PSR-2 standard (item 2.2) require omission of the closing tag. PHP manual itself (1,2), Wordpress, Drupal and many other PHP software I guess, advise to do so. If you simply make a habit of following the standard (and setup PHP-CS-Fixer for your code) you can forget the issue. Otherwise you will always need to keep the issue in your mind.

Bonus: a few gotchas (actually currently one) related to these 2 characters:

  1. Even some well-known libraries may contain excess line endings after ?>. An example is Smarty, even the most recent versions of both 2.* and 3.* branch have this. So, as always, watch for third party code. Bonus in bonus: A regex for deleting needless PHP endings: replace (\s*\?>\s*)$ with empty text in all files that contain PHP code.
查看更多
一个人的天荒地老
6楼-- · 2018-12-31 01:48

Well, there are two ways of looking at it.

  1. PHP code is nothing more than a set of XML processing instructions, and therefore any file with a .php extension is nothing more than an XML file that just so happens to be parsed for PHP code.
  2. PHP just so happens to share the XML processing instruction format for its open and close tags. Based on that, files with .php extensions MAY be valid XML files, but they don't need to be.

If you believe the first route, then all PHP files require closing end tags. To omit them will create an invalid XML file. Then again, without having an opening <?xml version="1.0" charset="latin-1" ?> declaration, you won't have a valid XML file anyway... So it's not a major issue...

If you believe the second route, that opens the door for two types of .php files:

  • Files that contain only code (library files for example)
  • Files that contain native XML and also code (template files for example)

Based on that, code-only files are OK to end without a closing ?> tag. But the XML-code files are not OK to end without a closing ?> since it would invalidate the XML.

But I know what you're thinking. You're thinking what does it matter, you're never going to render a PHP file directly, so who cares if it's valid XML. Well, it does matter if you're designing a template. If it's valid XML/HTML, a normal browser will simply not display the PHP code (it's treated like a comment). So you can mock out the template without needing to run the PHP code within...

I'm not saying this is important. It's just a view that I don't see expressed too often, so what better place to share it...

Personally, I do not close tags in library files, but do in template files... I think it's a personal preference (and coding guideline) based more than anything hard...

查看更多
栀子花@的思念
7楼-- · 2018-12-31 01:50

As my question was marked as duplicate of this one, I think it's O.K. to post why NOT omitting closing tag ?> can be for some reasons desired.

  • With complete Processing Instructions Syntax (<?php ... ?>) PHP source is valid SGML document, which can be parsed and processed without problems with SGML parser. With additional restrictions it can be valid XML/XHTML as well.

Nothing prevents you from writing valid XML/HTML/SGML code. PHP documentation is aware of this. Excerpt:

Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the < ?php ?> tags to remain compliant with standards.

Of course PHP syntax is not strict SGML/XML/HTML and you create a document, which is not SGML/XML/HTML, just like you can turn HTML into XHTML to be XML compliant or not.

  • At some point you may want to concatenate sources. This will be not as easy as simply doing cat source1.php source2.php if you have inconsistency introduced by omitting closing ?> tags.

  • Without ?> it's harder to tell if document was left in PHP escape mode or PHP ignore mode (PI tag <?php may have been opened or not). Life is easier if you consistently leave your documents in PHP ignore mode. It's just like work with well formatted HTML documents compared to documents with unclosed, badly nested tags etc.

  • It seems that some editors like Dreamweaver may have problems with PI left open [1].

查看更多
登录 后发表回答