Should You Close PHP Tags? The Debate Continues…

I was amazed at the response to my recent article, Should You Close Your PHP Code Tags? I didn’t think it would be controversial or cause so much debate among developers!

To recap, closing PHP tags (?>) are entirely optional if you’re coding a PHP-only file and there’s no intermingled HTML. Files containing single class definitions are good candidates.

Omitting the closing tag has another benefit: it becomes impossible to accidentally add white space to the end of the file. Therefore, output cannot be sent to the browser before HTTP page headers are modified.

Many respondents considered this to be a hack and stated that PHP programmers should simply fix their code. For others, omitting the closing tag prevented the possibility of errors — even if none ever existed. This can be especially useful for projects with many contributors using different IDEs.

Respondents mostly fell into one of three groups:

  1. PHP developers, perhaps working on larger projects or teams, where omitting the closing ?> was useful, recommended, or a documented coding-standard.
  2. Coding purists, possibly with a background in XHTML or XML, who considered missing tags to be wrong.
  3. Developers from other disciplines who considered the discussion to be ridiculous!

According to the SitePoint poll, a third of PHP developers did not use a closing tag, a third considered that bad practice, and third didn’t realize it could be omitted.

For the record, I often omit the closing tag. It makes no difference to the PHP interpreter or the browser so there’s little reason to include it. However, I can appreciate why some developers dislike the coding style.

Some interesting notions were raised. The first is that the interpreter could assume PHP code by default and allow escaping into HTML, e.g.


// PHP file
DoSomeStuff();
<?html
<p>output HTML</p>
?>
DoMoreStuff();

I suspect this idea is too revolutionary. It could possibly be added as a php.ini option, but it’d break existing applications and cause chaos.

However, pure PHP files was an idea with more potential. In essence, you’d specify that a file contained PHP code only. This could be achieved by:

  • using a special file extension, e.g. filename.pphp, or
  • using a modified include/require function, such as

include('filename.php', PHP_ONLY);

If this were implemented, your PHP code wouldn’t require opening or closing tags. In addition, the functionality could be added without affecting existing PHP applications — it would be backward compatible.

But, hey, it’s just an idea and may never go any further than this article. The PHP coding style debate will rage on…

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.reich-consulting.net/userproof/ coffee_ninja

    I read both articles, and I’ve been coding in PHP for a lot of years, and I just can’t wrap my head around why anyone thinks omitting the closing tag (“?>”) is bad coding. It’s a completely legal, documented, and expected behavior of PHP… in other words, its certainly not a hack!

    If you’ve ever written a function/class library file with stray white space that threw off the rest of your code, then you’ll understand why omitting the closing tag is useful.

    My final point: PHP is not XML or XHTML. I like using strict markup languages because they protect me from accidentally writing poorly nested tags. But PHP code is not XML, so there is absolutely no syntactic requirements stating that I need to close my PHP tags.

    • Anonymous

      I can’t believe this is such a big issue. Who cares? And ontop of that, if you got white-space, go remove it – don’t be lazy.

      • http://www.optimalworks.net/ Craig Buckler

        I didn’t think it would be such a big issue, hence the follow up article.

        Finding it is another matter — you might have a app with hundreds of PHP files. You could obviously write some white-space removal code, but why bother when there’s a far easier solution?

      • Anonymous

        White spaces have one uncomfortable feature – they are in most editors invisible.

        So no, don’t remove trailing spaces, remove ?> and never care about trailing spaces ever again.

      • AnonyMouse

        Some IDEs that aren’t PHP-centric automatically add a blank line to the end of files, because some C compilers require it.

        The fact that PHP even has an opening tag is so that you can embed it in HTML. The requirement for it to be used in all-PHP files (ala class definitions) is simply incidental due to its templating origins.

        There is no debate here; the closing tag shouldn’t be used in all-PHP files because NO benefit can come of using it, while there can be penalties to its use.

    • http://www.optimalworks.net/ Craig Buckler

      Thanks coffee_ninja. I agree — it’s not a hack or sloppy coding. It’s a safety net, sure, but that’s no bad thing. However, many people disagreed on the previous article.

      • http://www.reich-consulting.net/ coffee_ninja

        Looks like you’ve stirred up a bit of a holy war!

        I have the luxury (or burden) of rarely working with other programmers, so it’s interesting to me to read about how other people do things. Apparently they do it by telling people who do it differently how stupid they are. How unproductive! Leave it to the human race to take a medium perfect for rational discussion and turn into a bully pulpit….

        ?>

        :P

  • Martin Fjordvald

    What this study really shows is that at least one third of PHP developers are incredibly stupid.

    As for your PHP_ONLY suggestion. I don’t really think it’s worth it to be honest. Yeah you can save 5 characters but you suddenly need to worry about included files being accessed directly as they might then be outputted in plain text. Showing the world your shoddy code is usually not sane, if there’s no security flaws there’s usually plenty of things to ridicule. :)

    • Dave

      Included files being exposed shouldn’t be a problem nowadays. This can be easily avoided with an intelligent directory layout, an organized application design and a good configured webserver.

  • http://xslt2processor.sourceforge.net boen_robot

    I am the kind of person that feels a little dirty by omitting the PHP ending (I’d only omit it if demanded by a coding standard), and yes, I am indeed a supporter of anything X(HT)ML related, even though I know that’s not related to this particular issue.

    But I do like the PPHP idea. I’ll be glad to see that implemented with a separate pseudo MIME type (e.g. application/x-httpd-pphp) or a separate argument (in case of CGI/FCGI; e.g. “php-cgi.exe -p”). Such an option would make debugging the “headers already sent” error and the like much easier for newbies (assuming they start programming in PPHP from the get go; For compatibility’s sake, that won’t be the case initially of course).

    Hopefully someone at the PHP team could think about it, and do it for PHP6… and hopefully without the “<?html” syntax – if you really need to have pure HTML in a PHP file, there’s the current style PHP.

  • Pies

    The closing tag is useless and can be harmful. If you want it just to be purist about it, adjust your medication.

  • USPatriot

    Slow news day, Craig?

  • Andrew Fitzgerald

    I always leave them off and recommend the practice to others. I actually view it as smart coding, not laziness or sloppy coding. There is no need to mark the end of the file at all.
    It’s just extra code which opens the door for errors. So why even add it?

  • Andrew

    Drupal standards promote NOT closing (most of core is pure PHP) except in situations like templates, where one might type:
    <?php print t(‘My translatable text’); ?>
    Even there, they might omit the semi-colon which I disagree with (I always write it). PHP allows no ; when there is only ONE statement within. It’s a bad habit to get used to if you ask me. You can’t write
    <?php print $var_content
    func_call() // This isn’t JavaScript and you shouldn’t do this in Javascript either! ?>
    In terms of omitting ?> for large files that are purely PHP, I don’t care about debating because I follow standards we set as a company, or the project might dictate. One of the more annoying things about PHP is the fact that you have to write the starting <?php (or <? if you decide to have that on) in the first place! Even if you do php on the command line like in a shell script:
    #!/usr/bin/php -q
    This will print exactly as shown.
    <?php // Some code
    ?>
    We exit!
    END OF SCRIPT
    The only use for the entering and closing is that you can mix your printed text that needs no checks or formatting really (such as HTML with classes, which of course you’ll use CSS EXTERNAL style sheets for). Bash will require a print or printf or echo on every statement for printing, and same for many other common shell scripting languages.
    But anyway, stop debating, follow your own/company’s coding standards, and get back to work!

  • Key

    I am working with php about 7 years and never had issue with whitespace because when start new php file i automatically add and then begin programming. But usually i read documentation and decide us ?> or not. So i think that discussing about using ?> or not is waste of time.

    • http://www.optimalworks.net/ Craig Buckler

      Yeah, let’s not discuss it!…
      Opps.

  • Sky

    I dont get the talk about this…
    Its documented in PHP, so why the heck would it be “not strict” or “sloppy coding” ?
    I never close PHP tags since i discovered that it was not needed.
    Keep it simple, stupid :)

  • http://www.yacare.fr McBenny

    I was advised that the closing tag could (should) be omitted 2 years ago and if it shocked me at the beginning, I adpoted the technique.
    I even omit it at the end of “mixed” files, even when it’s a majority of HTML, if the last part of the file is PHP :
    <html>

    <?php
    if(…){
    ?>
    html… html… html…
    <?php
    }
    else{
    ?>
    html… html… html…
    </html>
    <?php
    }

  • Tom__

    Omitting the ending tag works fine because editors can handle it, too.

    If you introduce a complete new syntax, without any standard backing it up your break not only bc but the editing workflow.

  • http://www.patricksamphire.com/ PatrickSamphire

    I think it’s simply contextual. If you’re writing a robust application (e.g., a CMS) which is likely to have third parties using it, you’re unlikely to mix PHP and HTML, so leaving off the closing tag makes sense. But if, like me, you’re sometimes doing a quick snippet of PHP which won’t be reused, it’s sometimes easier to mix in HTML, and so you keep the closing tag. I’m not sure why people don’t just accept that there are multiple uses and work accordingly. We don’t actually need everyone to do everything just the same…

  • http://www.cemerson.co.uk Stormrider

    Personally, I never used to omit it, but always do now. I can see how it is useful, and there isn’t really any reason not to.

  • oelmekki

    “According to the SitePoint poll, a third of PHP developers did not use a closing tag, a third considered that bad practice, and third didn’t realize it could be omitted.”
    I’m pretty sure many people of the second third are people of the last one that don’t admit it.
    There are no good reasons to type more code if it implies more bug risks to achieve the exact same thing.
    And yes, imo, a good programmer *is* lazy. The less we have to focus on minor things, the more we can focus on (and enjoy) designing great features.

    • http://www.deathshadow.com deathshadow60

      See, to me omitting closures IS sleazy practice — it’s why I embraced XHTML.

      Though I’m firmly in the camp that this bull needs to go altogether. You want output it should be in a output pseudo-function like echo or print!

      If nothing else it would put a end to these code train wrecks of people opening and closing php ten times a line and the completely incomprehensible logic flow when people use if statements with them. (yes turdpress, I’m looking at you!)

    • Kyu

      My editor automatically adds opening/closing php tags when i create php files, so.
      1 – you suggesting that i delete the ?> part? which leads me to think,
      2 – The actual culprit here seems to be either careless coders (or
      inappropriate editors) adding a white space.
      and yeah, btw, developpers aren’t lazy, just efficient :P

  • http://blog.phpdoc.info/ scoates

    Hi.

    I hacked your asssume-PHP-is-default idea into a preprocessor script:
    http://github.com/scoates/prep/tree/master/examples/assume_php/
    I’m sure it’s not very robust, but as you can see in the demo (below), it’s possible.

    S

    sarcasm:~/src/prep (master %)$ cat examples/assume_php/input.php
    // PHP file
    echo “This is from PHPn”;
    <?html
    <p>output HTML</p>
    ?>
    echo “This is also from PHPn”;
    sarcasm:~/src/prep (master %)$ php -d’extension=prep.so’ -d’prep.command=./examples/assume_php/assumer.php’ examples/assume_php/input.php
    This is from PHP

    <p>output HTML</p>
    This is also from PHP
    sarcasm:~/src/prep (master %)$

    • http://www.optimalworks.net/ Craig Buckler

      I’m very impressed — that’s amazing!

      I have one question: can I omit the closing ?> on HTML-only files?!!

      • http://xslt2processor.sourceforge.net boen_robot

        What’s the “.html” extension (or the MIME type “text/html”) used for again?

        One more reason I said earlier that I wouldn’t want the “<?html” syntax… the “to omit or not to omit” question then becomes cyclic.

        Currently, you have two ways of writing pure HTML (in “.html” file and in a “.php” file with no “<?php” in it), and no single one of writing a pure PHP file, and with the script above, you get a non robust (and I’d assume slightly slower) one way.

    • Mikushi

      Why not just use XHP?
      http://github.com/facebook/xhp
      That’s freakin amazing ;)

      As for the closing tag, as a Lead Dev, i personally shoot on sight anybody putting closing tags on PHP only files :) . Got screwed couple of time by those, freakin Windows IDE, i see them because i use Vim to code, but most of the Windows based IDE don’t show them, so now, not putting closing tags is part of our coding standards.

      • Kyu

        i specifically configured my IDE to show whitespace in a different color just to be sure. granted my IDE also adds the start/end tags for me as soon as i create the file so that’s not a problem for me. (though by your “standards” i’d be screwed i guess xD) in the end i guess it just comes down to how we manage to cope with the problem in a coherent and efficient manner.

  • jperras

    find . -name ‘*.php’ | xargs sed -r -i -e ‘s/ss*$//’

    And you’re done. Don’t let trailing whitespace troll your code.

  • Key

    Why to use and that shows that if you now how to handle problem there are no problem :)

  • mcksmith

    The php file extension is a heads-up for the server that somewhere in the document there will be PHP code that needs to be interpreted by the PHP processor. (Although there is no actual requirement to have any PHP code in the file).

    The opening PHP tag tells the server when to stop parsing the file as regular text and start interpreting it as PHP. This may occur anywhere in file which is why, to this day, the opening tag needs to be included even if the page is entirely PHP – a web server will parse a file with a php extension as regular text until an opening PHP tag is found.

    The purpose of the closing tag is to let the server know that it is to stop interpreting the page as PHP and go back to parsing the page as regular text. This is why the closing tag can (and should be) omitted if there is no regular text to parse after the PHP code.

    The opening and closing PHP tags have nothing to do with well-formed structure – they are simply markers for the web server to know when to start and stop interpreting the file as PHP.

    Why tell the server to stop interpreting the file as PHP and go back to parsing it as regular text if there is no regular text to parse? Especially if some stray whitespace inadvertently finds it way into the file after the closing PHP tag.

  • Wardrop

    It’s things like this which highlight PHP’s roots all to clearly. There are plenty of good solutions to this problem, as well as all the others such as PHP’s ugly procedural API. People look at fixing these problems as “not possible” because it breaks backwards compatibility. Given how much there is to be gained by completely breaking backwards compatibility in a future PHP release, I don’t see breaking backwards compatibility as a significant problem. Such a decision to do so would truly liberate PHP and give it new found life. If something’s not done, what will happen sooner or later, is everyone will simply jump ship to a different programming language.

    This is precisely why I jumped ship to Ruby. After learning Ruby, it’s hard to even consider going back to PHP, not because it’s not a capable language, but because it’s just such an ugly mess. It’s still stuck in the 90′s. If however PHP were to clean up its API, start making better assumptions (assume a PHP file is in fact a PHP file), and slightly improve on it’s object-orientated feature-set, I’d definitely use it wherever appropriate. But right now, I’m avoiding PHP like the plague.

    By the way, I learnt programming in PHP, and have been using it for web development for the past 3 or 4 years. I even still “think” in PHP. It’s only in the passed 6 months or so that I’ve really explored other languages, from C# and Java, to Scala, Clojure and Ruby. The latter 3 definitely highlight PHP’s old-fashioned ways.

    That’s my two cents anyway.