Working around register_globals

bool import_request_variables ( string types [, string prefix])

As with register globals, import_request_variables() has been removed entirely in modern versions of PHP, so you should not be relying on it, or even using it.

In order to provide a middle ground for users who did not want to use the superglobals but also did not want to enable register_globals, the function import_request_variables() was introduced. Import_request_variables converts variables inside the superglobal arrays into variables in their own right, at takes two parameters: a special string of which types of variables to convert, and the prefix that should be added to them.

The special string can contain "g" for GET variables, "p" for POST, "c" for cookies, or any combination of them. The prefix works in almost the same way as the prefix to extract() does - the difference is that it does not automatically add an underscore, which means that scripts relying on older, insecure functionality can just use import_request_variables to get back to the old manner of working. As with the prefix used in extract(), the string is appended to the beginning of the names of each variable created to ensure there is no naming clash with existing data.

Here are some examples:

import_request_variable("p", "post");
import_request_variable("gp", "gp");
import_request_variable("cg", "cg");

Note that the order of the letters in the first parameter matters - in "gp" for example, any POST variables that have the same names as GET variables will overwrite the GET variables. In other words, the GET variables are imported first, then the POST variables. If we had used "pg", it would have been POST then GET, so the ordering is crucial.

Once import_request_variables() is used, you can use the new variables immediately, like this:

print $_GET['Name'];
import_request_variables("g", "var");
print $varName;

Note that it is $varName rather than $var_Name, which is different from the behaviour the extract() function. If you don't specify a prefix, or if the prefix is empty, you will get a notice outputted to the screen to warn you of the security issue.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Magic quotes >>

Previous chapter: register_globals

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.