使用 Register Globals

Warning

本特性已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除

可能 PHP 中最具争议的变化就是从 PHP » 4.2.0 版开始配置文件中 PHP 指令 register_globals 的默认值从 on 改为 off 了。对此选项的依赖是如此普遍以至于很多人根本不知道它的存在而以为 PHP 本来就是这么工作的。本节会解释用这个指令如何写出不安全的代码,但要知道这个指令本身没有不安全的地方,误用才会。

当 register_globals 打开以后,各种变量都被注入代码,例如来自 HTML 表单的请求变量。再加上 PHP 在使用变量之前是无需进行初始化的,这就使得更容易写出不安全的代码。这是个很艰难的抉择,但 PHP 社区还是决定默认关闭此选项。当打开时,人们使用变量时确实不知道变量是哪里来的,只能想当然。但是 register_globals 的关闭改变了这种代码内部变量和客户端发送的变量混杂在一起的糟糕情况。下面举一个错误使用 register_globals 的例子:

Example #1 错误使用 register_globals = on 的例子

<?php
// 当用户合法的时候,赋值 $authorized = true
if (authenticated_user()) {
    
$authorized true;
}

// 由于并没有事先把 $authorized 初始化为 false,
// 当 register_globals 打开时,可能通过GET auth.php?authorized=1 来定义该变量值
// 所以任何人都可以绕过身份验证
if ($authorized) {
    include 
"/highly/sensitive/data.php";
}
?>

当 register_globals = on 的时候,上面的代码就会有危险了。如果是 off,$authorized 就不能通过如 URL 请求等方式来改变,这样就好多了,尽管初始化变量是一个良好的编程习惯。比如说,如果在上面的代码执行之前加入 $authorized = false 的话,无论 register_globals 是 on 还是 off 都可以,因为用户状态被初始化为未经认证。

另一个例子是关于会话的。当 register_globals = on 的时候,$username 也可以用在下面的代码中,但要意识到 $username 也可能会从其它途径进来,比如说通过 URL 的 GET。

Example #2 使用会话时同时兼容 register_globals on 和 off 的例子

<?php
// 我们不知道 $username 的来源,但很清楚 $_SESSION 是
// 来源于会话数据
if (isset($_SESSION['username'])) {

    echo 
"Hello <b>{$_SESSION['username']}</b>";

} else {

    echo 
"Hello <b>Guest</b><br />";
    echo 
"Would you like to login?";

}
?>

采取相应的预防措施以便在伪造变量输入的时候给予警告是完全有可能的。如果事先确切知道变量是哪里来的,就可以检查所提交的数据是否是从不正当的表单提交而来。不过这不能保证变量未被伪造,这需要攻击者去猜测应该怎样去伪造。如果不在乎请求数据来源的话,可以使用 $_REQUEST 数组,它包括了 GET、POST 和 COOKIE 的所有数据。详情可参见本手册的来自 PHP 之外的变量

Example #3 探测有害变量

<?php
if (isset($_COOKIE['MAGIC_COOKIE'])) {

    
// MAGIC_COOKIE 来自 cookie
    // 这样做是确保是来自 cookie 的数据

} elseif (isset($_GET['MAGIC_COOKIE']) || isset($_POST['MAGIC_COOKIE'])) {

   
mail("admin@example.com""Possible breakin attempt"$_SERVER['REMOTE_ADDR']);
   echo 
"Security violation, admin has been alerted.";
   exit;

} else {

   
// 这一次请求中并没有设置 MAGIC_COOKIE 变量

}
?>

当然,单纯地关闭 register_globals 并不代表所有的代码都安全了。对于每一段提交上来的数据,都要对其进行具体的检查。永远要验证用户数据和对变量进行初始化!把 error_reporting() 设为 E_NOTICE 级别可以检查未初始化的变量。

更多关于模拟 register_globals 为 on 或 off 的信息,请见此 FAQ

Note: Superglobal 可用性说明:

自 PHP 4.1.0 起可以使用 Superglobal 数组,例如 $_GET$_POST,和 $_SERVER,等等。更多信息请阅读手册中的 superglobals 章节。

User Contributed Notes

tomas at hauso dot sk 18-Nov-2016 01:30
for PHP5.4+ you can use registry pattern instead global

final class MyGlobal {
    private static $data = array();

    public static function get($key) {
        return (isset(static::$data[$key]) ? static::$data[$key] : null);
    }

    public static function set($key, $value) {
        static::$data[$key] = $value;
    }

    public static function has($key) {
        return isset(static::$data[$key]);
    }

}
// END OF CLASS

$var1 = 'I wanna be global';

MyGlobal::set('bar', $var1 ); // set var to registry

function foo(){
    echo MyGlobal::get('bar'); // get var from registry
}

foo();
steve at dbnsystems dot com 07-Sep-2016 02:23
The following version could be even faster, unless anyone may come with a good reason why this wouldn't be a good practice:

<pre>
function unregister_globals() {
    if (ini_get(register_globals)) {
        $array = array('_REQUEST', '_SESSION', '_SERVER', '_ENV', '_FILES');
        foreach ($array as $value) {
            $$value = [];
        }
    }
}
</pre>
thewordsmith at hotmail dot com 14-Apr-2015 10:09
//Some servers do not have register globals turned on. This loop converts $_BLAH into global variables.
foreach($_COOKIE as $key => $value) {
    if(!is_array($value)){
        ${$key} = trim(rawurldecode($value));
        //echo "$key $value<br>";
    }
    else{
        ${$key} = $value;
    }
}
foreach($_GET as $key => $value) {
    if(!is_array($value)){
        ${$key} = trim(rawurldecode($value));
        //echo "$key $value<br>";
    }
    else{
        ${$key} = $value;
    }
}
foreach($_POST as $key => $value) {
    if(!is_array($value)){
        ${$key} = trim(rawurldecode($value));
        //echo "$key $value<br>";
    }
    else{
        ${$key} = $value;
    }
}
foreach($_REQUEST as $key => $value) {
    if(!is_array($value)){
        ${$key} = trim(rawurldecode($value));
        //echo "$key $value<br>";
    }
    else{
        ${$key} = $value;
    }
}
foreach($_SERVER as $key => $value) {
    if(!is_array($value)){
        ${$key} = trim(rawurldecode($value));
        //echo "$key $value<br>";
    }
    else{
        ${$key} = $value;
    }
}
chirag 21-Feb-2015 01:26
Fatal error: Cannot re-assign auto-global variable _POST

Final Solution for php 5.4 and above version

$a =  $_POST;
function add($_POST;){
 echo $_POST['a'];
 echo $_POST['b'];
}
add($a);
chirag176 at yahoo dot com dot au 20-Feb-2015 09:52
$mypost = secure($_POST);

function AddBatch($mypost,$Session_Prefix){
...
}
arman_y_92 at yahoo dot com 28-Aug-2014 02:44
To all those fans of this insecure functionality (which I'm glad is now turned off by default) , you can just use extract() to achieve a similar goal more securely (unless you overwrite local variables with $_GET or $_POST data).
elitescripts2000 at yahoo dot com 30-Aug-2013 04:23
<?php

/* Forces all GET and POST globals to register and be magically quoted.
 * This forced register_globals and magic_quotes_gpc both act as if
 * they were turned ON even if turned off in your php.ini file.
 *
 * Reason behind forcing register_globals and magic_quotes is for legacy
 * PHP scripts that need to run with PHP 5.4 and higher.  PHP 5.4+ no longer
 * support register_globals and magic_quotes, which breaks legacy PHP code.
 *
 * This is used as a workaround, while you upgrade your PHP code, yet still
 * allows you to run in a PHP 5.4+ environment.
 *
 * Licenced under the GPLv2. Matt Kukowski Sept. 2013
 */

if (! isset($PXM_REG_GLOB)) {

 
$PXM_REG_GLOB = 1;

  if (!
ini_get('register_globals')) {
    foreach (
array_merge($_GET, $_POST) as $key => $val) {
      global $
$key;
      $
$key = (get_magic_quotes_gpc()) ? $val : addslashes($val);
    }
  }
  if (!
get_magic_quotes_gpc()) {
    foreach (
$_POST as $key => $val) $_POST[$key] = addslashes($val);
    foreach (
$_GET as $key => $val$_GET[$key]  = addslashes($val);
  }
}

?>
lester burlap 23-Mar-2009 09:00
It would make this whole issue a lot less confusing for less-experienced PHP programmers if you just explained:

- $myVariable no longer works by default
- $_GET['myVariable'] works just fine

I'm embarrassed to say it's taken me six months since my ISP upgraded to PHP5 figure this out.  I've completely rewritten scripts to stop using GET variables altogether.

I'm dumb.
claude dot pache at gmail dot com 15-Jan-2009 05:52
Beware that all the solutions given in the comments below for emulating register_global being off are bogus, because they can destroy predefined variables you should not unset. For example, suppose that you have

<?php $_GET['_COOKIE'] == 'foo'; ?>

Then the simplistic solutions of the previous comments let you lose all the cookies registered in the superglobal "$_COOKIE"! (Note that in this situation, even with register_global set to "on", PHP is smart enough to not mess predefined variables such as  $_COOKIE.)

A proper solution for emulating register_global being off is given in the FAQ, as stated in the documentation above.
moore at hs-furtwangen dot de 14-Jul-2008 01:19
I had a look at the post from Dice, in which he suggested the function unregister_globals(). It didn't seem to work - only tested php 4.4.8 and 5.2.1 - so I made some tweaking to get it running. (I had to use $GLOBALS due to the fact that $$name won't work with superglobals).

<?php
//Undo register_globals
function unregister_globals() {
    if (
ini_get('register_globals')) {
       
$array = array('_REQUEST', '_FILES');
        foreach (
$array as $value) {
            if(isset(
$GLOBALS[$value])){
                foreach (
$GLOBALS[$value] as $key => $var) {
                    if (isset(
$GLOBALS[$key]) && $var === $GLOBALS[$key]) {
                       
//echo 'found '.$key.' = '.$var.' in $'.$value."\n";                   
                       
unset($GLOBALS[$key]);
                    }
                }
            }
        }
    }
}
?>

The echo was for debuging, thought it might come in handy.
Dice 15-Apr-2008 09:46
To expand on the nice bit of code Mike Willbanks wrote and Alexander tidied up, I turned the whole thing in a function that removes all the globals added by register_globals so it can be implemented in an included functions.php and doesn't litter the main pages too much.

<?php
//Undo register_globals
function unregister_globals() {
    if (
ini_get(register_globals)) {
       
$array = array('_REQUEST', '_SESSION', '_SERVER', '_ENV', '_FILES');
        foreach (
$array as $value) {
            foreach (
$GLOBALS[$value] as $key => $var) {
                if (
$var === $GLOBALS[$key]) {
                    unset(
$GLOBALS[$key]);
                }
            }
        }
    }
}
?>
Ruquay K Calloway 01-Apr-2008 05:59
While we all appreciate the many helpful posts to get rid of register_globals, maybe you're one of those who just loves it.  More likely, your boss says you just have to live with it because he thinks it's a great feature.

No problem, just call (below defined):

<?php register_globals(); ?>

anywhere, as often as you want.  Or update your scripts!

<?php
/**
 * function to emulate the register_globals setting in PHP
 * for all of those diehard fans of possibly harmful PHP settings :-)
 * @author Ruquay K Calloway
 * @param string $order order in which to register the globals, e.g. 'egpcs' for default
 */
function register_globals($order = 'egpcs')
{
   
// define a subroutine
   
if(!function_exists('register_global_array'))
    {
        function
register_global_array(array $superglobal)
        {
            foreach(
$superglobal as $varname => $value)
            {
                global $
$varname;
                $
$varname = $value;
            }
        }
    }
   
   
$order = explode("\r\n", trim(chunk_split($order, 1)));
    foreach(
$order as $k)
    {
        switch(
strtolower($k))
        {
            case
'e':    register_global_array($_ENV);        break;
            case
'g':    register_global_array($_GET);        break;
            case
'p':    register_global_array($_POST);        break;
            case
'c':    register_global_array($_COOKIE);    break;
            case
's':    register_global_array($_SERVER);    break;
        }
    }
}
?>