Mon, 20 Oct 2008

Fixing crap PHP applications

— SjG @ 1:18 pm

I regularly end up in the situation where I have to fix a crap PHP application.

The latest one has lots and lots of PHP 3.x-era code, that references hashes without quoting the index, e.g.,

$foo = $bar[baz]

Now, the PHP interpreter understands this in actuality. It figures out that since the constant is not defined, the programmer probably meant that the index should be ‘baz’. It does, however, throw a well-deserved warning.

The code I’m trying to fix throws lots and lots of warnings. Rather than wade through all the warnings to find which ones are important, I started with the following:

find . -name \*.php -exec grep -ne '\[[^\$0-9\'\''\"]' {} \;

The thousands of lines of output convinced me bigger guns were needed.

So we got ugly.

find . -name \*.php -exec perl -p -i.bak -e 's/\[([^\$\d\'\''\"]+)\]/\[\'\''$1\'\''\]/g' {} \;

Note that that’s one line, and that WordPress seems to want to change some single quotes into back-ticks. Don’t be fooled!

All those extra backslashes and single quotes are to allow passing single-quotes within the regex, and not have bash consider them problematic.

Also note that this could be catastrophic if you have regular expressions in the code you’re operating on — do a diff with the backup version, and merge back the regexes.

I’m sure there are far more elegant solutions… primary among them, not using crap PHP apps in the first place!

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.