Configuring Lighttpd for CakePHP

I tried a few days ago to install a CakePHP project of mine on a lighttpd web server. As expected, its clean URLs didn’t work, so I set out to find a solution.

One possible solution is the one outlined in the CakePHP manual. The solution uses the mod_magnet module (which basically runs a Lua script to do the rewriting), and I found it to be overkill. I was looking for a simple solution based only on mod_rewrite, something like the solution for WordPress.
Continue reading Configuring Lighttpd for CakePHP

Trailing Whitespace Causes a Session to Be Destroyed in CakePHP

While working on a new project using CakePHP, I’ve come across a weird problem. In one of the controllers, the session always came out as invalid, as

$this->Session->valid()

always returned false. I tried debugging this weird stuff, and it looked like all the session variables were unset. Using

$this->Session->error()

to get the last error returned “Config doesn’t exist”. After further debugging, “Config” turned out to be an internal array that is saved by CakePHP to the session and holds various internal data (some of it is used for validation, like a user-agent hash). I kept printing more and more debugging data, as well as looking at CakePHP’s trac system.

I found an interesting bug (ticket #4217), and it looked very promising, as it almost fully described my problem. Unfortunately, the solution offered didn’t seem to work for me. But it inspired me to try starting the session manually using session_start() instead of using Cake’s startup and activate methods of the Session Component.

I found out that session_id() returned an empty string. Luckily, calling session_start() directly from the controller gave me a lead. The session seemed to work well, but a nasty error about headers already being sent showed up.

A little more investigation led me to realize that I had a trailing newline after my closing PHP tag in that controller file. Deleting this trailing whitespace completely solved the problem. There was no need anymore to manually start the session. It’s pretty annoying that such a small thing as a trailing newline can cause such seemingly unrelated problems in CakePHP’s session handling.

Maybe CakePHP should add a little debug notice when the session doesn’t start because headers were already sent. This can be done by modifying the else statement in the __startSession() method in cake/lib/session.php (line 557 in version 1.2.0.6311). I wonder what the reason was for not informing the developer when such an event happens, as I don’t see why someone would deliberately try to start the session after sending the headers. I think it only happens by mistake, at least most of the time.