How can I emulate register_globals in PHP 5.4 or newer?

。_饼干妹妹 提交于 2019-11-28 20:46:06
sectus

You can emulate register_globals by using extract in global scope:

extract($_REQUEST);

Or put it to independent function using global and variable variables

function globaling()
{
    foreach ($_REQUEST as $key => $val)
    {
        global ${$key};
        ${$key} = $val;
    }
}

If you have a released application and do not want to change anything in it, you can create globals.php file with

<?php
extract($_REQUEST);

then add auto_prepend_file directive to .htaccess (or in php.ini)

php_value auto_prepend_file ./globals.php

After this the code will be run on every call, and the application will work as though the old setting was in effect.

Just in case it may be helpful, this is the code suggested on php.net to emulate register_globals On:

<?php
// Emulate register_globals on
if (!ini_get('register_globals')) {
    $superglobals = array($_SERVER, $_ENV,
        $_FILES, $_COOKIE, $_POST, $_GET);
    if (isset($_SESSION)) {
        array_unshift($superglobals, $_SESSION);
    }
    foreach ($superglobals as $superglobal) {
        extract($superglobal, EXTR_SKIP);
    }
}

Source: http://php.net/manual/en/faq.misc.php#faq.misc.registerglobals

From the PHP manual, it says that:

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

However, a Google search revealed this method on Ubuntu Forums:

Nope, it's finally gone for good. Whatever site is still using globals had, what, half-a-dozen years or more now to fix the code?

The quickest solution is to create the globals from scratch by running this code at the beginning of the app:

Code:

foreach ($_REQUEST as $key=>$val) {
    ${$key}=$val;
}

You have to be careful that any variable created this way isn't already defined in the remainder of the script.

You can force this code to be run ahead of every page on the site by using the auto_prepend_file directive in an .htaccess file.

I'd strongly recommend looking at the code that requires register_globals and changing it so that it works properly with it being disabled.

In php.ini before:

auto_globals_jit = On

After:

auto_globals_jit = Off
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!