Somacon.com: Articles on websites & etc.

§ Home > Index > Web Development

Import Request Variables in PHP

A more elegant way to import request variables in PHP.

Usage

Here's an elegant way to import request variables from $_REQUEST into the global namespace. All you have to do is specify the names of the variables that your script will use in $selectRequestVariables, similar to declaring them. The next few lines will add those variables to both the $GLOBALS hash and the global namespace. Don't put this code in a function, because variables can't be added to the global namespace from within a function (only to $GLOBALS).

Advantages

This method has several advantages. It avoids the security problems associated with importing every variable in $_REQUEST. It also avoids the notice caused by not using ugly prefixes with import_request_variables. Finally, if a variable is unset, it will be set to empty string, avoiding the uninitialized variable notices. You still need to validate the input, but you don't need to litter your code with "if isset".

Source Code

The code snippet below is granted to the public domain. The validation examples below it are just for demonstration purposes.

$selectRequestVariables = array("Borat","AliG","Bruno");
foreach($selectRequestVariables as $selectRequestVar) {
    // split across lines for readability
    eval('$GLOBALS["'.$selectRequestVar.'"] = $'.
        $selectRequestVar.' = isset($_REQUEST["'.
        $selectRequestVar.'"]) ? $_REQUEST["'.
        $selectRequestVar.'"] : "";');
}


// boolean validation example
$Borat == "1" ? $Borat = true : $Borat = false;

// string validation example
preg_match("/rapper/", $AliG) == 0 ? die("AliG must be a rapper") : true;

// numeric validation example
is_numeric($Bruno) ? $Bruno = intval($Bruno) : die("Bruno must be flamboyant");

Commentary

As PHP progresses, it continues to display more warnings and notices. Of course, you could lower the error_level, but that is poor development practice that typically leads to unmaintainable and unreadable code. PHP also continues to increase security requirements. For instance, PHP 4.2.0+ disables the register_globals directive by default, and PHP 6.0 eliminates it entirely. The above technique may provide a more modern and convenient way to import request variables.

Notices

The following notices are avoided by using the above technique.

PHP Notice: Undefined index: test
When you use $_REQUEST["test"] and "test" is not a variable in the request.
PHP Notice: import_request_variables(): No prefix specified - possible security hazard
When you use import_request_variables without specifying a prefix.

Created 2006-11-08, Last Modified 2011-07-24, © Shailesh N. Humbad
Disclaimer: This content is provided as-is. The information may be incorrect.