Securely Retrieving GET or POST Data

My page on Retrieving GET or POST Data provides some simple code to retrieve all passed values. Unfortunately that code effectively removes most of the security benefit of having register_globals disabled in PHP (as it is by default in the more recent versions of PHP). With some slight modifications to that code we can add most of that security back in.

$allowed = array("parmone","parmtwo");
$q = explode("&",$_SERVER["QUERY_STRING"]);
foreach ($q as $qi)
  if ($qi != "")
    $qa = explode("=",$qi);
    list ($key, $val) = $qa;
    if (in_array($key,$allowed) && $val)
      $$key = urldecode($val);
reset ($_POST);
while (list ($key, $val) = each ($_POST))
  if (in_array($key,$allowed) && $val)
    $$key = $val;

The only thing that this code does differently is that the $allowed array needs to be set to a list of the names of the fields that the routine expects to receive. The added code within the loops check that the variable name passed to the page is found somewhere in the $allowed array. If it is found then that variable is loaded with the passed value (as before) but if it is not then that variable is ignored.

This code is in fact the simplest solution for anyone who has obtained a script that assumes that register_globals will be enabled to allow that script to run on a host where register_globals is disabled. Simply add the above code (with $allowed = array("");) at the top of the script to be converted. Run the script and see what variables are listed in error messages because the script is assuming that register_globals is enabled. Add these variable names into the $allowed array and you should find that the script will then function correctly.

Adding this code has two advantages over getting register_globals enabled. The first is that your web host may not permit register_globals to be enabled because of security issues. The second is that even if they do permit you to request to have register_globals be enabled, you have to ask them to do that for you. You can add this code to the script yourself without needing to involve your host.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow