PHP's closing tag

2012-02-24

Several years ago I came across the “closing tag” issue of PHP. Ever since then it is one of the first things I show someone new to PHP development.

What is the issue?

Pure PHP files, those that start with the opening <?php tag and end with with the closing ?>, should omit the closing tag at the end of the file.

Why is this important?

Anything after the closing tag ?> will be returned. This includes whitespace.

For example:

<?php
    echo "foo";
?>bar

Will return:

foobar

This is expected, you may have wanted some HTML in place of “bar”, but what isn’t expected, is the whitespace you can’t see.

Imagine for a moment that instead of bar in the example you have    . Just some whitespace that inadvertently made it into your file. Now when the example returns you will get foo   . This might be OK, I mean, nobody ever looks at whitespace right?

Well what happens when you have a few PHP scripts that return heavily formatted strings for use in AJAX or EDI?

Sometimes you can trim the excess whitespace off, but sometimes you don’t have that luxury.

A few years back I needed to figure out why some of my companies EDI files where getting extra spaces right after the customer number and right before amount due. In our case it meant a rare customer had their bill reduced 90%. Turned out the previous maintainer had a single space after the closing tag in a few of the files.

It took a while to find and correct this error, there were tons of files, and back then I didn’t use an editor that you could turn on show white space.

tl;dr-

Save your self some time and energy debugging. Skip the closing tag ?> in pure PHP files to keep whitespace from ruining your day.