PHP Practices: Buffering your autoload

I spent 2 hours working on a problem with PHP, Doc-Types, and a website. We started to see symptoms across our website where we would get a 12px space on the top of the page on IE7 (Internet Explorer 7) and FF3 (FireFox 3). We started combing through the HTML markup our website was returning, and parsing it via FireBug I could tell that something was causing our page to parse in correctly.

Later I discovered that an extra space was being added before the Doc-Type was inserted, so it was invalidating our Doc-Type and threw off the parsing of our page on several browsers. After hours of research and debugging I found out a class file that we were loading via autoloading was leaking a space to the output. I couldn’t figure out where, or how. I read and re-read the code 4-5 times before I decided to give up. I couldn’t figure out where the extra space was coming from.

So I decided to “buffer protect” all my code in my autoload. Basically, I did something like this:

function __autoload($class_name)
// Start an output buffer to catch all text sent to browser
// Load the file
// Get the contents and save them to no variable. If you wanted to see what was sent to the output
// you can get it by doing $var = ob_get_contents();
// Stop the output buffer and clear its content.

That would ensure that if a class on accidently send text to the output, this would protect against it. I hope this helps someone.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close