Archive for February, 2009

What the…?> PHP and unwanted whitespace

Wednesday, February 18th, 2009

While working with some older PHP projects we’re migrating to our servers for some clients, I’ve run into a number of “unwanted whitespace” errors in PHP code. Unwanted whitespace can cause header output errors when they proceed a header call, or causing binary files loaded with readfile to break.

Typically, the cause of these errors has been the use of ?> followed by one or more whitespace characters. The extra whitespace was either added by the original author (and overlooked thanks to a low error_reporting level) or by a none-too-helpful FTP client.

After spending too long hunting down the whitespace (made necessary by the use of unnecessary code), I Twittered about the problem and a deluge of discussion followed.

Tradition and Convention vs. Need

According to the PHP manual on the topic of instruction separation, the use of ?> at the end of a file is completely optional. That said, the use of ?> has been standard fare for decades. At this point in history, most of us are so used to seing it dangling uselessly at the bottom of our code, that removing it feels painful or even dangerous.

Personally, I’d never thought to question it’s existence until I read the Doctrine ORM for PHP coding standards. Coding standards typically consist of a four spaces vs. tab debate, where one should put one’s curly braces, and class naming conventions. When I read Doctrine’s, I was surprised to find them start out with the requiring that ?> not be used at the end of files.

Since then, I’ve found other projects that require it be left off and, most recently, spent hours frustrated by the fact that someone before me didn’t leave it off.

Necessity, the Mother of Invention Convention

There seems to be growing movement among projects to drop the use of ?>. Most PHP coders, however, aren’t a part of those project. Many of us stumble across these things by accident, and overlook them as an oddity of a particular project (as I originally did with Doctrine) rather than a best practice for all PHP code. My hope is that my Twittering about it, this blog post, and subsequent debate/promotion/usage of the practice will save us all time down the road.

Discontinuing the use of ?> where it’s not needed is one way we can make the world a better place. No longer using PHP 3 and 4 and moving to PHP 5 would also help, but that’s another blog post.

© 2007-2012 BigBlueHat
Close
E-mail It