As of PHP 5.4, the register_globals
feature has been removed from php. If you still need the feature, this post is for you.
What is register_globals?
register_globals
is an internal PHP setting (a php.ini directive) that registers $_REQUEST
super global array’s elements as variables. For example if you submit a value in a form, via POST
or GET
request methods, with an input field name username
, PHP will automatically register a variable $username
and assign it value of the input field username
.
Why register_globals was removed?
PHP is not a very strict language. If you make mistakes, it often leaves you with Notices and Warnings without stopping execution, unless a very serious problem occurs. PHP lets you use uninitialized variables and issues just a Notice that is not displayed by PHP (unless you enable strict error reporting). A script that follows anything less than very strict coding style, is exposed to security threats and bugs if the feature register_globals
is enabled.
register_globals Alternative
It is highly recommended that you do not use register_globals
because it allows anyone to inject variables into your script. But, for the fact that most of the developers that use register_globals
develop simple websites that often do not have an authentication system, or other features that should make them conscious for their choice about secure methods and practices, I have decided to write a simple script that can help them implement similar feature again in PHP. Here is the script. You can copy it anywhere in your page:
function register_global_array( $sg ) { Static $superGlobals = array( 'e' => '_ENV' , 'g' => '_GET' , 'p' => '_POST' , 'c' => '_COOKIE' , 'r' => '_REQUEST' , 's' => '_SERVER' , 'f' => '_FILES' ); Global ${$superGlobals[$sg]}; foreach( ${$superGlobals[$sg]} as $key => $val ) { $GLOBALS[$key] = $val; } } function register_globals( $order = 'gpc' ) { $_SERVER; //See Note Below $_ENV; $_REQUEST; $order = str_split( strtolower( $order ) ); array_map( 'register_global_array' , $order ); }
And then call this function at the start of your page, or call it when you want to use the feature.
register_globals( );
You can also choose which Super Global Arrays to use for registering variables.
register_globals( 'GPCFRES' );
Where G
stands for $_GET
, P
for $_POST
, C
for $_COOKIE
, F
for $_FILES
, R
for $_REQUEST
, E
for _ENV
and S
for $_SERVER
.
If you use HTML form field name that cannot be used as a PHP variable name, this function still registers a variable, but you will have to use that variable dynamically.
echo ${'1_invalid_name'}; echo ${'another-invalid-variable-name'};
And one last thing, did you notice the unnecessary use of $_SERVER
, $_ENV
and $_REQUEST
in the above code on Line 20? The use is not unnecessary actually. Read this Interesting Super Globals post for details on this.