excepting death: die vs exceptions in php 5

March 6, 2009

If you kill your scripts with ‘die’ or ‘exit’  your script instantly becomes less flexible.

Why not throw an Exception and let it bubble to the top? The script will terminate anyway, but provides better error reporting & gives you a chance to handle the error more gracefully. There is barely ever a time you want to simply kill your script.

Consider the following snippet, typical of many web applications (edit from objects & error handling answer on stackoverflow)

class DatabaseConnectionException extends Exception {}

class Database {
    public function connect($user, $pass, $db) {
        //Connection stuff.
        //Assume we failed with a bad username.
        $baduser = true;
        if($baduser) {
            throw new DatabaseConnectionException('Username (' . $user. ') is invalid.');
         if($badpass) {
             // etc

$db = new Database();

$user = 'Maynard James Keenan';
$pass = '46and2';

try {
    $db->connect($user, $pass, $db);
} catch (DatabaseConnectionException $e) {
    die("I cannot connect to the database");

Think of others when you die.

If you are working on a project and it suddenly stops and tells you:

“I cannot connect to the database.”

What useful information does this tell me? What database? Where? Why wasn’t it found? Is it trying to connect to the same database I’ve been working with? To figure out what’s going on, I have to grep for the error message, which I then discover is inside a die() then start putting in random echo, debug_print_backtrace, etc calls in the code to figure out what went wrong, why and where.

We could make this better by adding some additional debugging context information as the parameter for die…

die('I cannot connect to the database:' . $e);

But this still doesn’t tell us a whole heap and really depends on what information our programmer has deemed us worthy enough to receive from the exception call.  While this is fine for simple cases, when it gets a bit more complex (eg an error is introduced futher up the call stack) in come the backtraces and echos.

Let’s say this was going on a production site. What happens if the db goes offline for some reason? Our end users are going to see some pretty ugly messages.

Secondly, if someone else is using your code and wants to adjust how that error is handled, (eg figures out a way the error can be recovered from)… all they need to do is try/catch the error.

Thirdly, You get control over what happens when the exception is thrown by setting up an exception handler with set_exception_handler. Maybe down the track you don’t want this to die, or you’d prefer your script to terminate on a pretty “Oops, something went wrong” page for the user. Not easily done done when your code is littered with die() statements. Don’t be scared to just not catch exceptions... unless of course you can do something useful with it (eg recover, or formulate a quality error message). Other than the speed for hacking some debugging only statements, I can’t see any benefit of using any die() statements anywhere in your project.


Vim Essentials

February 10, 2009

I found this great little tutorial on vim. Presented well and covers the essentials for beginners to experienced. Even if you use Vim every day, it’s such an expansive  app so it’s always good to rehash on some of the features you’ve forgotten.

View this document on Scribd

The first 50 or so pages are general (non php specific), and the remainder would probably have parallels in their respective languages. Enjoy :wq

Downloading Music or Media from Online Media Players, using Firebug

June 29, 2007

Sometimes a flash media player will request an mp3 or video file from a server somewhere, load it and play it. To the average user this file cannot be listened to or downloaded without going to the website and using that media player.

You can use Tools -> Page Info -> Media to locate the urls all the files that are loaded when the page loads but unfortunately this list isn’t updated as  scripts (javascript/flash) make futher requests for other files after the initial page load.

The Firebug firefox extension does just this though, and is a very handy resource when working with scripts as you can monitor all the incoming files, their progress and status. It also shows you the url of all the resources requested (eg, mp3s, flash content, etc) . We can use this to track down the URL of the media content we are trying to save to our computer.

  1. First Install Firebug and restart your browser.
  2. Open the page that contains the content you want to save
  3. Open Firebug in a new window by going to Tools -> Open Firebug in a New Window
  4. Go to the ‘Net’ tab, this displays all the requests for resources and their statuses (stati?).
  5. If you are looking for a music file, you can either try find the file with a .mp3 extension, but sometimes the file may not have an extension or the file name is so long you can’t read the extension…simply look for the file with the largest file size (usually in megabytes) and you should be on the right track.
  6. Copy the url of this file (it’s the leftmost column) to the clipboard.
  7. Paste this into your web browser and you should get the option to save the file. Save it. And you’re done.
  8. Woot.

If you can’t find the file, it might well be that the mp3 is embedded within the flash file. This is unlikely but possible…simple way around this is to save the flash file to your computer. Load the file in your browser by copying the url to the address bar and save the file by going to file -> Save Page As and you should be able to save the file to your computer. Though, clearly, you won’t be able to play the flash file on your ipod or burn it to a CD (though SOME more advanced mobile phone may be able to play the content). I’ll write some instructions for recording and saving audio sometime. You can use the freeware tool AoA Audio Extractor to rip audio from flash files. 🙂

Also note you can retrieve almost all the content you view on the web offline by searching through your cache. To search through your chache type about:cache into your broswer window. (works with firefox and firefox derivatives only. Check your browser’s documentation (try pressing F1) for further details.).

Edit: You can also try extensions like Download Helper for an easy way to rip most content.