Maintaining broken code

Time moves on. Technology improves, sometimes taking care of bad decisions in the past, making it necessary to fix things related to that. PHP changed over the years in small and subtle ways, from register_globals, short_tags, autoglobals, and will hopefully continue to improve in the years to follow. But some things are not a design fault in PHP. Some things are a direct cause of little to no thought in the process of using PHP. PHP itself is a tool, and a powerful one. Unfortunately, it is as good of a tool, as the person using it. And the person who wrote this, was definitely a tool:

// unset unwanted variables created by register_globals
$var_list = get_defined_vars();
$safelist = array('_GET', '_POST', '_COOKIE', '_SERVER', '_ENV', '_FILES', '_REQUEST', '_SESSION');
foreach($var_list as $name => $value)
{
   if(array_search($name, $safelist) === FALSE)
   {
       unset($$name);
   }
}
unset($var_list, $name, $value, $safelist);

I died for an hour, figuring out what the hell caused $GLOBALS to be null, in a piece of code after the one above. Apparently, $GLOBALS did not show up in get_defined_vars() in older PHP versions, a thing which kicks you in the ass five years later.

As you see, the author asumed that:

  • register_globals was turned on (it wasn’t!)
  • that the auto globals list was fixed and would not change

When doing destructive things (ie, variable variables + unset), one should give some afterthought to what needs to be accomplished. Obviously the goal here was security, but the end result was a defunct product. Especially since it was using $GLOBALS originally.

Disclaimer: Code was written by third party and ordered by a client about 5 years ago. While being far from documented, and including some comments in finnish (dear god, perkele vittu), it is still in pretty good shape. It fails in what I observe to be a common pitfall of similar software today - it tries to do too much.

I myself use variable variables, but not as stupidly as the example above. The main problem with them is trying to explain them to anyone else than yourself. But if you know what you’re doing, they can be very powerful, like many other PHP features.

I need anger management classes after this.

While I have you here...

It would be great if you buy one of my books:

Buying a copy supports me writing more about similar topics.

For business inqueries, send me an email. I'm available for consultany/freelance work. See my page for more detail..