Monday, June 8, 2009

PHP is a messy hack.

So I'm building a php site for a client from scratch.... I know I know I should be using a framework of some sort. However I don't want to bill my client for learning Cake or what have you. Anyway I decided to implement (a simple version at least) Rails' "flash" functionality for the site. If you're unfamiliar with Rails' flash, its basically a kick ass way to pass data from one page to another.

You put a message such as "Thanks for signing up!" Into the flash and then redirect the user to their new account page (or whatever) then as long as the account page is setup to display "flash" messages, It will show you message and then remove it from the flash. This is really handy for displaying one time messages without sending the user to a basically useless page.

So I cooked up this:

// Make sure sessions are active.
session_start() or die("session failed to start");

// Displays and clears flash data
function display_flash()
//Check for and display flashes
echo '
' . $_SESSION['flash_notice'] . "
echo '
' . $_SESSION['flash_warn'] . "

Then all I need to do is run the following in the page I want the flash to show up in:




Where I want the flash to show up. And here is where things get messy. So the next step is redirecting users to a page setup to display the flash. The standard way of redirecting with PHP is:

header("Location: URL");

Which is a horrible hack and only works if header info hasn't already been sent. I thought I could work around it so I started pasting it all over my existing pages. Turns out that it worked some of the time but not all the time, and it seemed totally random to me.

Luckily for me I'm working on a VPS from Rimu hosting which means that I have root access to a virtual server for $20 per month! So I found http_redirect in the pecl_http package. Installed PECL and then installed pecl_http. I replaced all instances of `header("Location: Url");` with `http_redirect("page.php");" and now my flashes work just fine!

Lesson learned, PHP does not work out of the box. It is simply broken. The pecl_http library rocks! Don't get hosting from a provider who doesn't support it.