in Web Development

Using PHP exec() and exceptions

I’ve been lucky enough the last couple of days, to be able to rewrite some code that’s needed it.  One of the things that I took the time to explore during this rewrite was exceptions.  Now I’m just using them very basically and to some programmers much more educated than me they’d cringe with my use, but they are working.  However I ran into a problem that I had a hell of a time solving.  In the end it was my ignorance, but I’m sure others out there are having the same issue.

I was doing something like this (exact syntax isn’t important here)

if (!exec(“convert resize 50% photo.jpg photo_thumbnail.jpg”))
throw Exception (“Photo resizing gone bad!”);

When I’d look in my directory where I was converting them I’d see that one thumbnail would be created and the rest wouldn’t. The easy solution was to go back and not use Exceptions, but that wouldn’t be right so I trudged on.  And just as I was about to leave work yesterday it occurred to me!  There’s a second argument that you can pass to exec() that stores the results of what exec() executes and that is what needs to be tested for. So I ended up with the following code:

exec(“convert resize 50% photo.jpg photo_thumbnail.jpg”,$aResult);

if (!empty($aResult))
throw Exception (“Photo resizing gone bad!”);

I hope this helps someone else out as it stopped me for a bit!