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:

  1. register_globals was turned on (it wasn't!)
  2. 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.

- Tit Petric

While I have you here...

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

I promise you'll learn a lot more if you buy one. Buying a copy supports me writing more about similar topics. Say thank you and buy my books.

Feel free to send me an email if you want to book my time for consultancy/freelance services. I'm great at APIs, Go, Docker, VueJS and scaling services, among many other things.