Google analytics code

Saturday, September 19, 2009

PHP: Simple register_globals workaround

Working with an old php4 project in php5 can expose some bad programming practices and create bugs. The first problem is relying on register_globals. I don't want to turn this on because it injects variables into the page scope. I also don't want to update the whole project to not rely on it.

The simple way around this is to write something that injects the variables into the project scope. This function will read all the variables from the url and inject them into the project scope. You should never rely on register_globals, but if you don't want to update old code this is an easy workaround.

function register_globals()
{
  //if register_globals is on then return
  if(ini_get("register_globals")) return;

  //inject URL vars into scope
  foreach($_REQUEST as $key=>$item)
  {
    $GLOBALS[$key] = $item;
  }
}

2 comments:

  1. I wrote a script to register globals and track down usage of them. check it out here if you want to remove the dependency entirely.

    http://www.phpclasses.org/package/8386-PHP-Log-the-usage-of-registered-global-variables.html

    ReplyDelete

If you found this page useful, or you have any feedback, please leave a comment.