Should You Close Your PHP Code Tags?

By | | PHP

Even those with a modest grasp of PHP know that code must be enclosed within special <?php and ?> tags.

note: Alternative PHP tags

You may also be aware that PHP code can be delimited with the lesser-used <script language="php"> and </script> tags.

If short_open_tag is enabled within php.ini, you can use <? and ?> although they should be avoided if you’re embedding code within XHTML or XML.

Finally, you can use the ASP-style <% and %> tags if asp_tags is set within php.ini.

However, if your file contains just PHP — and no escaped HTML code — the closing ?> tag is entirely optional. Many developers argue that unnecessary code should be removed but there’s another reason you could consider scrapping the closing tag.

Assume we have a PHP function library named library.php:


<?php
// library functions
function DoStuff() {
	// code
}
?>

The library’s included inside our main entry file, index.php:


<?php
include('library.php');
// write a header
header('X-Demo: Example');
// set cookie
setcookie('TestCookie', 'Example');
?>
<p>End of index.php file.</p>

Unfortunately, 2 warnings with the same message appear when this page is loaded:

Warning: Cannot modify header information - headers already sent

Or worse, if you could be running in a live environment where warnings have been disabled and no message appears. In either case, neither the header or the cookie is set and that could cause critical application problems.

What’s causing the error? You can’t see it, but there’s a space character following the closing ?> in the library.php file. When it’s included at the top of index.php, that space is sent as page content to the browser — along with all the necessary HTTP headers. Once the first block of content has been sent, it’s not possible to set additional headers or cookies.

note: PHP output buffering

Modern versions of PHP set the output_buffering flag in php.ini. This buffers your HTML output and sends it when your PHP code has been processed or once the buffer reaches a limit (e.g. 4,096 bytes). You can also use PHP’s ob_start() and ob_end_flush() to implement your own buffering functionality.

If output buffering is enabled, you can set HTTP headers and cookies after outputting HTML because returned code is not sent to the browser immediately.

Note that older versions of PHP and some ISPs do not enable output buffering — it hits server performance and requires more memory. Even if you’re certain buffering is always enabled, it’s good practice to set HTTP headers and cookies before sending page content.

Your PHP application could include dozens of library or class files. As you can imagine, it can be difficult to hunt down additional spaces, carriage returns, or any other characters following a closing ?>.

Fortunately, there’s an easy fix. If you omit the closing ?> in all your PHP-only code files, the error simply can’t occur — the parser will ignore whitespace.

It’s a solution, but would you use it? It makes me feel a little dirty…

Do you already omit the closing ?> tag? Would you adopt the practice? Or does it just feel wrong?

Written By:

Craig Buckler

Craig is a Director of OptimalWorks, a UK consultancy dedicated to building award-winning websites implementing standards, accessibility, SEO, and best-practice techniques.

Website
>> More Posts By Craig Buckler

 

{ 62 comments }

Yannick Mortier September 26, 2010 at 9:44 am

I think the discussion has been going long enough and I was really wondering while reading some of your arguments.

Somehow to me it looks completely clean to have

at the end.

Maybe this is because I also write a lot of C++ and somehow associate the

<?php

at the beginning with the

#include

using xyz.xyz;

etc. since I also put the includes in the php script directly under the leading <?php

Seems like everyone has a different point of view.

Yannick Mortier September 26, 2010 at 9:45 am

Somehow my post got destroyed… Several parts are missing

Darryl Patterson September 25, 2010 at 12:35 am

We don’t use tags to go into and out of PHP code, we escape into and out of PHP code. Tags must be closed as most tagged documents (like XML docs) must be representable as a tree. PHP is a programming language that lives within documents, so we use a string of escape characters to escape into PHP when we need PHP code, and escape out of PHP to go back to the doc type we’re in. If, after escaping into PHP, we have no need to output from the surrounding doc type, there’s no need to escape out of PHP. This has nothing to do with clean code.

In the case of XHTML docs, I only escape out of PHP if I have additional XHTML to send out to the browser. For files that contain only PHP code, I have no need to escape back into XHTML.

romaninsh September 23, 2010 at 5:20 pm

I keep my code clean, but when designers and clients have access to the code, they sometimes add spaces at the file end for no reason. Happened to me few times, so I prefer keeping it safe and omit ?>.

I’d love to have a mode where are disabled completely, then PHP is PHP and not some sort of mix between HTML and PHP. That’s what template engines are for.

deathshadow60 September 24, 2010 at 1:40 pm

What Romaninsh just said I’ve been saying since the first day I tried PHP – get rid of the stupid malfing crap altogether! If it’s going to be a programming language, treat it as one instead of some stupid half-assed mix.

If nothing else it would get rid of these idiotic scripts people write where they open and close php five times a line making their logic flow completely illegible… and plug about a dozen security holes in the process. Security 101, a library file called directly should never output anything. Goes hand in hand with “everything should be wrapped in functions” ([i]and people wonder why I call turdpress insecure by design[/i])

That said, if you are going to open something, you should **** close it. It’s what I hate about the people who sleaze out HTML 4 any old way and why I embraced XHTML regardless of the “It’s not real XHTML” bull [i](like there is ANY practical use for that XML application garbage anyhow)[/i].

Hell, it’s what bothers me about doctypes — they don’t even follow the syntax rules of the file formats they’re applied to.

Of course, omitting a closing tag just because some other coder is a retard that might ignore the rules is no reason to be omitting the closing tag.

Anonymous September 22, 2010 at 7:28 pm

Including the ?> can also lead to extra whitespace in your code. ZFW commonly doesn’t use the ?> end tags in their files. By all means… omit away.

pointbeing September 21, 2010 at 6:53 pm

Old news ;)

Only teasing, but this was blogged back in February of last year:
http://pointbeing.net/weblog/2009/02/php-closing-tags-considered-harmful.html

ranj1729 September 21, 2010 at 5:20 pm

I always prefer to omit php closing tag. There are 2 reasons for which I opt this habit.
1. PHP parser has a default property of adding closing tag when it includes any external php file or execute any php file. So we don’t need to explicitly add closing tag as it is already a property of the parser.
2. In recent days lots of XSS hacking like iframe injection is happening in many sites. So if you do not close php tag ( with ?>) then embaded scrtpt or iframe code can be treated as php and so throw error.By which at least, we can stop this kind of hacking.

Thanks!
ranj1729

Tom September 21, 2010 at 3:27 pm

Bottom line is… there’s no real reason not to (coding style shmoding style – learn to be flexible), and bunch of reasons why you should. Next!

Jonathon Hibbard September 21, 2010 at 5:14 am

The best solution would be if PHP required you to close a PHP tag, just as they require you to end your curly braces and parenthesis for conditional statements/function calls. It should be common sense that by PHP just “working” if you leave off the ending tag, it doesn’t equate to best practices.

Jon September 21, 2010 at 5:08 am

I’m kind of suprised people forget the early days of the web when it came to Internet Explorer: If you didn’t close the tag, IE didn’t care, it would just keep running like a champ.

Yet, when standards documents came into play and browsers became more standards compliant, we finally saw why we were suposed to close those tags. It was because tags were meant to be closed, and not closing them would be like not ending a sentence without an ending punctuation.

What this article (and unfortunatley, a lot of novice developers) say about not closing php tags is about bad practice.

Has anyone even stopped to say to themselves “Ok, php is actually complaining because I didn’t write my script correctly” ? No. Instead of fixing your mistake, you find a hack workaround. And guess what, it doesn’t do anything but make your code look incomplete, novice, and hacked up.

Either way, this is just my opinion. At the end of the day, every developer and team consider what they think and come up with their own solutions. While we may disagree, it’s really up to you. Not this article. Not fan boys. And definitely not Zend (who seem to have gotten a huge following even though every product (aside from the PHP engine) sucks.

Craig Buckler September 21, 2010 at 5:55 pm

While I’m programmed to automatically close tags, PHP is not mark-up. It’s a server-side language which can be embedded in HTML and, when you do that, you must close your PHP tags.

However, pure PHP files such as classes contain do not contain raw HTML. Closing the PHP tag makes no difference to the browser or the PHP interpreter. It’s not a hack — it simply reduces the possibility of introducing an error.

Jonathon Hibbard September 22, 2010 at 12:16 pm

Craig,
I don’t know man, it kind of sounds like it *is* a hack. There is a reason you don’t close it right? So that you can avoid a simple mistake like checking for whitespace at the end of your script?

To me, leaving it off because of that reasoning is a hack. A hack has many meanings obviously, but lately we translate it to “a quick and dirty workaround to fix an issue”. To me, leaving the closing tag off equates to just that.

I don’t think I will ever be convinced that leaving the PHP tag off is “sound”. What I really wonder is if the PHP development team figured out how to stop PHP from throwing these errors by just ignoring the whitespace in general, what would then be the reasoning for leaving the tag off?

Other than the fact that you “can”, I really don’t see a honest and meaningful reason behind it.

Craig Buckler September 22, 2010 at 5:54 pm

It’s not a hack in the traditional sense. Hacks normally solve problems by exploiting a bug or finding a workaround rather than addressing the root cause. This isn’t a hack because you may never cause or experience a problem even if your PHP tags are closed. It just makes it more difficult to accidentally introduce an error at a later stage.

The PHP interpreter should never ignore whitespace. It’d be easy to implement, but that whitespace could be essential for the HTML you’re working on.

Jonathon Hibbard September 23, 2010 at 11:02 am

While I don’t want to keep going back and forth, I still have to wonder if you realize what you said justifies (in a way) what I am trying to say :)

What do we define as a hack? One way (as you say) is to “find a workaround rather than addressing the root cause”. For what other reason are you leaving the tag off if not as a “workaround” for leaving whitespace at the end of your script instead of just addressing the issue: always check for white space.

To me, it comes down to common practices in development. If you know what the boundaries are for your language, then adhere to them.

Craig Buckler September 23, 2010 at 5:46 pm

Whether you consider it a hack or not doesn’t really matter. Omitting the tag means you never need worry about whitespace issues — which are difficult to trace in large projects involving dozens of developers using different IDEs.

it comes down to common practices in development

It’s common practice in PHP!

If you know what the boundaries are for your language, then adhere to them.

The closing tag is optional — it’s not a boundary.

Jonathon Hibbard September 24, 2010 at 12:18 pm

“…which are difficult to trace in large projects involving dozens of developers using different IDEs”

Thus why company standards are in place.

Either way, I guess we agree to disagree. Kind of like arguing if K&R is better than ANSI anyways =)

droope September 20, 2010 at 11:54 pm

Best practice: Remove the ending ?>

John J September 20, 2010 at 1:30 am

I’m sticking with using the closing ?> for the same reason I always use the closing tag. Yes, the code will run or the page will display properly if you leave it off, but it’s part of the correct syntax. There is the argument regarding preventing syntax errors, but the same error can occur, just as easily if there’s a leading space in the file just as a trailing space, which, personally, I have encountered much more than trailing space. The actual FIX for this is to double check your code. If your editor adds end of line characters, get a better editor: Aptana, Komodo, UltraEdit, heck, even Notepad.

One of the reasons PHP gets so little respect is because good enough “fixes” take the place of doing things right.

om September 21, 2010 at 5:31 am

The closing tag is optional, so not including it is NOT a syntax error. Have fun including it though, especially in six months when you can’t set cookies and have no idea why.

Tom September 21, 2010 at 3:31 pm

Most of the time, when I come across PHP these days, and in fact for a few years now, it omits the closing tag in files which end with PHP code. To me, as soon as usage is widespread enough and the engine is not complaining, that becomes the correct syntax.

Michael September 19, 2010 at 10:15 pm

I can’t remember the last time I used a closing PHP tag. I am a very pedantic kind of person with things like white space but I don’t feel dirty at all about leaving the PHP tag open.

Here’s a thought for you though Craig, do you feel dirty leaving a comma at the end of a set of array values? For example

$animals = array(
‘dog’,
‘cat’,
‘fish’,
);

That is equally as “dirty” as not closing a php tag, yet is done because it prevents you from producing erroneous code.

huarong September 19, 2010 at 12:07 pm

I have already omitted the closing ?> tag。
it ‘s no use.

Carl Welch September 19, 2010 at 4:51 am

I once spent entirely too much time debugging a problem with some PHP code I’d written to generate PDF output–the PDF files wouldn’t open in a reader. Turned out that I had an extra carriage return after the closing PHP tag. I’ve been leaving it off ever since.

mario September 19, 2010 at 12:19 am

The closing tag differentiates professional code from amateur scripts. It’s solely a newbie recommendation to leave out the closing tag. Web and PHP support forums are littered with questions about “headers already sent” errors. And it’s therefore a good practice to recommend newbies to leave them out for the sake of evading such mishaps. (It’s not foolproof however, since it basically just postpones the discovery.)
To me however it doesn’t speak of competency if someone obsessively strips out the closing tag. It’s often done just because of text editor woes, but too frequently it’s a lack of coding consistency and exactness attention.

Bobo Wieland September 18, 2010 at 11:25 pm

I never use the closing tag. Using it would make me feel dirty, not the other way around

Bertrand September 18, 2010 at 6:32 pm

I agree that while it is “safer” since no such error can occur, yes, it feels dirty for me as well. It’s like the if ( 0 == $a ), it avoids errors, but damn, just don’t do the error in the first place :-)

Sylvain Lévesque September 18, 2010 at 5:06 pm

Like all major framwork Zend, CodeIgniter and CakePHP we adopt this practice in all our projects. It’s so simple and can save à lot of time and damage.

IceBrain September 18, 2010 at 9:03 am

To me personally, I think having to include any PHP specific tags (<?, ) is an obsolete concept from the days when PHP was just a templating language.
You don’t need any opening/closing tags in Python, Java or any other language, because they don’t have the same roots.

I think no tags should be required; they could be used, optionally, when writing templates, but you’d use it backwards: start an HTML block with ?>, and then close it with <?
PHP code should be the default, and HTML secondary.

"By omitting this tag you introduce the issue of problems if you are parsing some XML data."
If you're depending on having <?php to have your XML well parsed, you're doing it wrong. Why are you parsing XML directly through the PHP interpreter?
If you're trying to generate XML using values from a PHP script, please don't use an XML template. We have XML generating engines for those purposes. Hand-writing XML with mixed PHP code is terrible.

"Additionally by using the <?php vs the <? saves almost nothing in the execution time vs the risk of somebody taking advantage of a mistake or inserting an extra <? in your code causing it to fail."
Who? How?
If you mean other devs, then you're not testing the code, and if you mean users, *sanitize, sanitize, sanitize*!

Wardrop September 23, 2010 at 11:13 am

I was about to say the same thing IceBrain. If a page is given to the PHP interpreter for parsing, the interpreter should assume the file is a php file. You should only have to use PHP tags as a way to tell the interpreter to “leave this portion as is”. PHP has so much mess inherited from it’s roots as you say (just look at the procedural and inconsistent API), which is precisely why I’m making Ruby my web development language of choice.

logic_earth September 18, 2010 at 7:59 am

I leave it off in my PHP-only files. There is no reason to have.

Diego September 18, 2010 at 7:56 am

I don’t ever use the closing tags on my php-only files. The only thing I do is putting a comment /* EOF */ to mark the end of file. On almost all frameworks it is actually a recomended practice.

Donny Kurnia September 18, 2010 at 1:51 pm

Agree with this. CodeIgniter suggest the same.

Origami Girlfriend September 18, 2010 at 5:43 am

It’s better not to close the php tag – sometimes you have 50 library files, and you’re not the only coder. What if someone leaves trailing lines? You’re screwed. Some editors leave trailing spaces just because you clicked in a wrong place. *You* might be doing it all right, but omitting the closing tag will solve problems for other people too :)

James Chevalier September 18, 2010 at 5:17 am

If you’re using CodeIgniter, then it’s part of the Style Guide to *not* use PHP closing tags. Over at http://codeigniter.com/user_guide/general/styleguide.html#php_closing_tag it states:

The PHP closing tag on a PHP document ?> is optional to the PHP parser. However, if used, any whitespace following the closing tag, whether introduced by the developer, user, or an FTP application, can cause unwanted output, PHP errors, or if the latter are suppressed, blank pages. For this reason, all PHP files should OMIT the closing PHP tag, and instead use a comment block to mark the end of file and it’s location relative to the application root. This allows you to still identify a file as being complete and not truncated.

James Morrison September 18, 2010 at 4:59 am

I’m a WordPress developer and always leave the closing ?> off in theme files, plugins and functions (basically everything except modifying core files).

It makes no difference to the functionality (ie it works with or without) and avoids the chance of whitespace causing a problem.

bkennedy September 18, 2010 at 4:48 am

Omitting the closing tag as a workaround for cleaning up coding errors? And Zend requires omitting them? This is one of those places where developers of other languages would laugh at us PHP devs. It’s a sloppy coding practice just to cover up another sloppy coding practice. Some day it will bite you in the butt.

Unless I’m wrong, html, xml, etc won’t validate strict without closing tags. Why should it be allowed -nay, encouraged- in PHP?

Anonymous September 18, 2010 at 11:46 am

PHP is a server-side language, leaving the PHP tag open will not affect your client-side code such as HTML or XML. It’ll will keep validating perfectly fine.

This is not a way to clean up coding errors, it’s a way to prevent them, you’re not hiding errors you’re simply creating a situation where what would usually be an error is no longer such.

If a non-PHP dev laughs at this then the PHP dev is laughing right back at the non-PHP dev for not understanding why it’s being done.

Aaron M. September 18, 2010 at 12:01 pm

PHP inside of HTML/XML template files should be closed. The Zend Framework coding standard does require closing them in those cases. However, calling the practice of leaving the closing tag off of a class or other script that is not intended to produce output by its mere inclusion a “sloppy coding practice just to cover up a sloppy coding practice” is useless flaming or evidence of a total misunderstanding of the matter being discussed here. No one is arguing for violating HTML/XML standards. Those standards are irrelevant when no markup is being created.

brothercake September 18, 2010 at 6:50 pm

This summarises my feelings on the issue.

The whole premise here is to omit the closing tags to workaround an error; so fix the damn error. Or alternatively, can’t PHP be clever enough to handle that whitespace situation?

Either way, abusing syntax to fix implementations is wrong. It’s the PHP equivalent of non-validating CSS hacks.

Craig Buckler September 18, 2010 at 10:48 pm

It’s not an error workaround — it simply prevents the possibility of an error occurring.

PHP can’t fix the whitespace situation because it’s perfectly reasonable to mix PHP and HTML code in the same file. In some cases, that whitespace could be fundamental — PHP shouldn’t attempt to second-guess what the developer is trying to achieve.

Anonymous September 20, 2010 at 11:25 pm

“can’t PHP be clever enough to handle that whitespace situation?”

Sure it can. As the original post suggest, the problem is only in individual libraries when whitespace occurs at the END OF THE FILE. So PHP only needs to check if thre is ANY WHITESPACE CHARACTER after the closing tag, and ignore whatever it finds there. It’s like one line of regexp.

Mike Girouard September 18, 2010 at 4:48 am

100% agree with Matthew.

Simply put: The benefits far outweigh the drawbacks. It’s considered a best practice industry-wide.

Sure, it’s easy to take the cocky approach and say “just write good code” but good luck taking that approach when you lead or work on a team of developers. Furthermore, there are several editors out there who’s default option is to include a trailing return.

That problem is multiplied by the number of files in your library and I think we all have better things to do with our client’s time/money than chase around issues that can arise from leaving in the closing tag.

Gary Jones September 18, 2010 at 4:31 am

The Genesis Theme Framework for WordPress has also adopted the practice of leaving off closing delimiters at the ends of files, particularly in the child theme functions.php files where amateur coders are more likely than regular developers (who do know about such issues) to end up with additional whitespace causing the error.

We don’t always clear values from variables to free up memory, as we know PHP itself will deal with it at a suitable time, so there’s no reason not to let PHP deal with this issue as well.

Matthew Weier O'Phinney September 18, 2010 at 4:15 am

You write, “It’s a solution, but would you use it? It makes me feel a little dirty…,” but you never explain what about the practice you dislike. To the contrary, you provide a ton of fodder as to why you *would* want to omit the closing tag.

Most of the reasons you cite are why we decided in the Zend Framework coding standards to require omitting the closing tag — it helps reduce potential errors (particularly when you you have a codebase as large as ours, with as many contributors as we have).

Craig Buckler September 18, 2010 at 10:38 pm

It’s simply a matter of coding style. I’ve been writing XHTML and XML for years, so not closing tags — even PHP ones — doesn’t feel right! That said, I think it’s a good practice, would recommend it for large projects and often do it myself.

cranial-bore September 24, 2010 at 8:40 am

But it’s not comparable to an XHTML tag.
XHTML elements will always exist in a document full of lots of other elements, and the point is to avoid having them overlap incorrectly or have ambiguity about where one ends.

A PHP only file is not sharing a space with other elements. It’s just PHP code. Nothing else. It ends when the file ends, nothing dirty about it.

ahallicks September 28, 2010 at 12:39 am

For this reason I prefer top include a closing PHP tag. Not because I feel it will or won’t benefit me, or my code, but because I have always had the strictest mentality in mind when it comes to coding.

That is why I pick XHTML over HTML, it looks cleaner, and if you want it to validate, you’ve got to get it right. I agree, for the most part, that removing the closing tag is beneficial in a lot of circumstances, and have been asked to use it in my work place. But my own code will always remain strict, closing what I feel should be closed and where.

At the end of the day, it’s down to personal preference, as with most things.

matipl September 19, 2010 at 12:30 am

You’re right. I also omitting the closing tag.

Joseph Scott September 18, 2010 at 3:49 am

I prefer leaving off the closing PHP tag when possible.

erlicthemad September 18, 2010 at 7:47 am

Not a good idea. By omitting this tag you introduce the issue of problems if you are parsing some XML data. Additionally by using the <?php vs the <? saves almost nothing in the execution time vs the risk of somebody taking advantage of a mistake or inserting an extra <? in your code causing it to fail.

erlicthemad September 18, 2010 at 12:16 pm

Maybe this boy should read more carefully. I do agree with your statement. I misread it and thought you were referring to omitting the php in the opening tag. Sorry about that.

Joseph Scott September 18, 2010 at 12:24 pm

I wasn’t talking about the short tag, I was talking about the close PHP tag – ?> – when possible I prefer to leave it off.

Dave September 18, 2010 at 3:48 am

In one sentence: I would not remove php ending markup.

Code better is the solution. By coding better I mean, remove trailing spaces and line breaks from the end of my libraries, and use output buffering (and/or caching) to handle output.

erlicthemad September 18, 2010 at 7:43 am

Code better? Yes in a perfect world we all would make certain that there are no extraneous spaces of whitespace in a file, and that all your people involved in a project follow your PERFECT example of how to code. Then things will work fine. Otherwise I will prefer to not add the extra ?> to the end of the code and let my php engine consume any extra whitespace. Instead of count on human perfection to prevent issues from occurring.

Anonymous September 20, 2010 at 11:21 pm

This is actually a perfect example of a stupid interpreter…

Hardy September 18, 2010 at 3:42 am

You could also set your IDE to remove extra white space and turn tabs into spaces (4 of ‘em) on save. That will help with “gotcha” errors, and keep your code consistent.

Craig Buckler September 18, 2010 at 10:34 pm

That will help to some extent, but many IDEs only delete trailing whitespace at the end of lines — not at the end of files. Carriage returns could still be present.

Paul September 18, 2010 at 3:36 am

I actually use the ?> tag, but what are the benefits if I don’t use it? It is a good practice? I don’t think so, a good practice is to use clean code and this includes check this issue.

On the other hand, it is useful to use the same method on html files? I you can see, as I read some time, Google don’t use the neither the tag. Can this “hacks” help to improve the time to load the pages?

skunkbad September 23, 2010 at 11:38 am

Did you really read the article, or did you just post a comment? If you read the article, you wouldn’t ask what the benefits of dropping the closing ?> are.

James September 18, 2010 at 3:19 am

Being a Drupal developer I am used to leaving it off. I have found that Dreamweaver can have some code highlighting issues if the closing tag is left off.

Nicolas September 18, 2010 at 5:27 am

Same here. Sometimes Dreamweaver delete code and you can’t recover it.

Comments on this entry are closed.