Tech Blog

CakePHP whitespace gotcha

Posted At : November 26, 2008 12:03 AM 4 Comments

I've been playing around with CakePHP again (I looked at it a couple of years ago) for a small site I'm working on.

I came across this lovely error though when trying to do a redirect:

Warning (2): Cannot modify header information - headers already sent by (output started at /.../tests_controller.php:35) [CORE/cake/libs/controller/controller.php, line 587]

I couldn't see anything wrong with the code - but a quick google found the solution - I had extra whitespace in the controller which was causing the problem.

Removing the extra whitespace after the closing ?> tag fixed it up.

Update: As Danilo pointed out below - this is not a cakephp issue, but a general php one, which occurs if you try to send headers after anything has been output to the browser.

Cheers, Mark

4 Comments

ike 11/26/08 12:37 AM

Y'know shortly ago when I decided to put together http://www.woohooligan.com I decided to do it in PHP instead of ColdFusion. The reason was that I know that I tend to get "carried away" with CF and I figured using a language I wasn't familiar with would help me to curtail that and just do what was necessary to make the site work. That part of the plan worked, though I have to say... WOW, PHP is *UGLY*. If you beat the devil with an ugly stick while rolling him around in a pile of garbage and then compared him to a page of PHP code, I think you'd have to crown the devil Miss America. And one of the things I found most frustrating about it was the idea that white space means "SEND THIS TO THE BROWSER NOW!" ... umm... but there's no content, sir... "I DON'T CARE! IT'S A CHARACTER! IT HAS TO GO TO THE BROWSER YESTERDAY!!!" Doesn't make any damn sense, it's just a constant annoyance for no particular reason.

Tony G 11/26/08 3:13 PM

CFML was the language that I learned server-side web development on. Then I took a foray into PHP for a while (mostly because of the abundance of OS software in that language). But I reached a point where I couldn't take it anymore and I came running back to CF. So I agree with ike -- U-G-L-Y. What's interesting is that one of the most common criticisms you see from PHP folk about CF is that it has ugly syntax. So beauty really is in the eye of the beholder, it guess.

Danilo Celic 11/26/08 4:19 PM

For those reading this post, the issue is a PHP issue with whitespace being output after some headers are sent, and typically occurs when a redirect is requested further down in the code from the whitespace. This issue has nothing to do specifically with CakePHP as implied in the post title.

Mark Lynch 11/26/08 8:35 PM

Hi Danilo,
Thanks for pointing that out - and this post was definitely not meant to be a criticism of PHP or CakePHP.
Cheers,
Mark