Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 66
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
Uważam, że serwis jest najlepszy na świecie. Wykonany rzetelnie, a wszystkie skrypty sa dopracowane. Zamieszczony materiał godny mistrza. Jestem programistą od wielu lat i bez tego serwisu nie istnieje. Upraszacza życie każdemu programiście. Imponujący jest fakt, że do twórcy serwisu zawsze można się zwrócić z prośbą o pomoc i uzyskuje się ją w bardzo krótkim czasie. Najważniejsze w tym wszystkim jest to, że można korzystać z witryny za symboliczną opłatą.

Marcin Kowalski
Multinet Polska

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

Rozdział 29. Using Register Globals

Perhaps the most controversial change in PHP is when the default value for the PHP directive register_globals went from ON to OFF in PHP 4.2.0. Reliance on this directive was quite common and many people didn't even know it existed and assumed it's just how PHP works. This page will explain how one can write insecure code with this directive but keep in mind that the directive itself isn't insecure but rather it's the misuse of it.

When on, register_globals will inject (poison) your scripts will all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier. It was a difficult decision, but the PHP community decided to disable this directive by default. When on, people use variables yet really don't know for sure where they come from and can only assume. Internal variables that are defined in the script itself get mixed up with request data sent by users and disabling register_globals changes this. Let's demonstrate with an example misuse of register_globals:

Przykład 29-1. Example misuse with register_globals = on

<?php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
  
$authorized = true;
}

// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
   include
"/highly/sensitive/data.php";
}
?>

When register_globals = on, our logic above may be compromised. When off, $authorized can't be set via request so it'll be fine, although it really is generally a good programming practice to initialize variables first. For example, in our example above we might have first done $authorized = false. Doing this first means our above code would work with register_globals on or off as users by default would be unauthorized.

Another example is that of sessions. When register_globals = on, we could also use $username in our example below but again you must realize that $username could also come from other means, such as GET (through the URL).

Przykład 29-2. Example use of sessions with register_globals on or off

<?php
// We wouldn't know where $username came from but do know $_SESSION is
// for session data
if (isset($_SESSION['username'])) {

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

} else {

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

}
?>

It's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if the submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging. If you don't care where the request data comes from, you can use $_REQUEST as it contains a mix of GET, POST and COOKIE data. See also the manual section on using variables from outside of PHP.

Przykład 29-3. Detecting simple variable poisoning

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

  
// MAGIC_COOKIE comes from a cookie.
   // Be sure to validate the cookie data!

} 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 isn't set through this REQUEST

}
?>

Of course, simply turning off register_globals does not mean your code is secure. For every piece of data that is submitted, it should also be checked in other ways. Always validate your user data and initialize your variables! To check for uninitialized variables you may turn up error_reporting() to show E_NOTICE level errors.

For information about emulating register_globals being On or Off, see this FAQ.

Tablice superglobalne: uwaga na temat dostępności: Od PHP w wersji 4.1.0, udostępnione zostały tablice superglobalne takie jak $_GET, $_POST czy $_SERVER. Więcej informacji można znaleźć w rozdziale superglobals




User Contributed Notes

rumby328 at yahoo dot com
25-Jan-2006 02:04

Regarding mike at uwmike dot com's snippet, it appears that calling this code causes $GLOBALS to become recursive within itself with a quick check to get_defined_vars().

A better version of this code without using $GLOBALS with the desired result is:
<?php
if (@ini_get('register_globals'))
{
   foreach (
$_REQUEST as $key => $value)
   {
       unset($
$key);
   }
}
?>

While more effective, this method still leaves non-$_REQUEST vars, such as $_SERVER vars, set.  One could remove these by creating an array of vars to be removed.  Consider:
<?php
if (@ini_get('register_globals'))
{
  
$remove_vars = $_REQUEST + $_SERVER;
   foreach (
$remove_vars as $key => $value)
   {
       unset($
$key);
   }
}
?>


raphael at er-solution dot de
12-Jan-2006 01:52

I found something very interessting. That method puts a "$_POST", "$_GET", .... in front of your var :)

<?php
/*
   If Register_Globals=off an your code is already typed for Register_Globals=on, include that function
*/
function globals_off ()
{
   if (!
ini_get('register_globals'))
   {
      
h$types_to_register = array('GET','POST','COOKIE','SESSION','SERVER');
       foreach (
$types_to_register as $type)
       {
           if (@
count(${'HTTP_' . $type . '_VARS'}) > 0)
           {
              
extract(${'HTTP_' . $type . '_VARS'}, EXTR_OVERWRITE);
           }
       }
   }
}
?>


frantik
13-Dec-2005 01:29

To: remi at chillet dot com

You can use extract() to do the same thing (and it has options to not overwrite existing variables and other goodies).

http://www.php.net/manual/en/function.extract.php


htaccess
10-Dec-2005 01:32

if you can use .htaccess
use php_flag register_globals 0


walterh at maine dot edu
07-Dec-2005 07:12

larry at freakdog dot net writes:
>adding php_flag in .htaccess under apache 2 will cause internal server error. according to apache 2 manual, php_flag should goes to <virtual> or <directory> section.
YMMV, as this appears to work fine as of 2.0.55

It appears to work on 2.0.52 as well.  Might have been something fixed in one of the prior releases of 2.0.xx.


remi at chillet dot com
30-Nov-2005 12:46

To simulate register_globals under Apache 2, add these lines in top of code PHP

foreach($_POST AS $key => $value) { ${$key} = $value; }
foreach($_GET AS $key => $value) { ${$key} = $value; }


larry at freakdog dot net
20-Nov-2005 11:52

>adding php_flag in .htaccess under apache 2 will cause internal server error. according to apache 2 manual, php_flag should goes to <virtual> or <directory> section.
YMMV, as this appears to work fine as of 2.0.55


alan at xensource dot com
15-Nov-2005 06:00

From the PHP Manual page on Using register_globals:

Do not use extract() on untrusted data, like user-input ($_GET, ...). If you do, for example, if you want to run old code that relies on register_globals  temporarily, make sure you use one of the non-overwriting extract_type values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.


Dexter at dexpark dot com
06-Nov-2005 03:59

For Apache users or webhosters, you can set the
php_flag register_globals on/off in a VirtualHost context.


dyer85 at gmail dot com
05-Nov-2005 07:10

I'd suggest taking a look at php.net's source code for these user notes, if you want to get ideas on some nice ways to collect and validate user data.

http://php.net/source.php?url=/manual/add-note.php


hbinduni at gmail dot com
30-Oct-2005 10:06

[quote]
If you're under an Apache environment that has this option enabled, but you're on shared hosting so have no access to php.ini, you can unset this value for your own site by placing the following in an .htaccess file in the root:

php_flag register_globals 0
[/quote]

adding php_flag in .htaccess under apache 2 will cause internal server error. according to apache 2 manual, php_flag should goes to <virtual> or <directory> section.


mike at uwmike dot com
13-Oct-2005 06:10

If you're on a shared environment, and have no way of disabling register_globals, this little "unregister_globals" snippet could come in handy:

<?php
if (@ini_get('register_globals'))
   foreach (
$_REQUEST as $key => $value)
       unset(
$GLOBALS[$key]);
?>


Pichen at quantumlounge dot com
27-Sep-2005 04:44

To fix my code I used the above example, plus I had to run an extract from $_COOKIE 

<?php
if(!empty($_GET)) extract($_GET);
if(!empty(
$_POST)) extract($_POST);
if(!empty(
$_COOKIE)) extract($_COOKIE);
?>


ramosa (0) gmail dotty com
24-Sep-2005 06:24

Here's a one liner that works both with register globals on or off, and is even secure enough when it's on, as you make sure you init the var.

Using the ?: operator

$variable = isset($_GET["variable"]) ? $_GET["variable"] : "";


argentus at ukr dot net
14-Aug-2005 11:04

I have found out a method which seems to me the best. I've written my own version of extract. It works as follows:

<?php

safe_extract
($_POST, "post", array("param1", "param2"));

// and now I can use the following variables:

echo "param1 is <b>$post_param1_html</b><br />";

mysql_query("SELECT * FROM sometable WHERE something = '$post_param2_slashes'");

if(
$post_param1_unsafe != $post_param2_unsafe)
// do something.

?>

I think it to be more convenient than using the required functions manually and more safe than that, and surely much more safe than register_globals = On.

The code is very simple. You can write your own version, of course, but I'll also show mine:

<?php

  
function make_variables($key, $value, $prefix)
   {
      
$GLOBALS["{$prefix}_{$key}_unsafe"] = $value;
      
$GLOBALS["{$prefix}_{$key}_slashes"] = addslashes($value);
      
$GLOBALS["{$prefix}_{$key}_url"] = urlencode($value);
      
$GLOBALS["{$prefix}_{$key}_html"] = htmlspecialchars($value);
      
$GLOBALS["{$prefix}_{$key}_url_html"] = htmlspecialchars(urlencode($value));
   }

   function
safe_extract($array, $prefix, $keys)
   {
       if(
count(array_diff(array_values($keys), array_keys($array))) != 0)
           return
false;

       foreach(
$keys as $key)
          
make_variables($key, $array[$key], $prefix);

       return
true;
      
   }
?>


kcinick at ciudad dot com dot ar
19-May-2005 12:12

if you plan to use php_admin_value register_globals [0-1] inside <VirtualHost> in apache, forget it, it don't show any error messages in the configuration, but at the time of running, it enable and disables register_globals at random request, if you need to customize this param to multiple virtual host, put it in a <Directory> directives, it works fine there...

PD: same for safe_mode, etc...


lexcomputer at gmail dot com
08-May-2005 05:42

If your have already a thousand of variables in your php script and you have only GET and POST method you can use this :
<?php
if(!empty($_GET)) extract($_GET);
if(!empty(
$_POST)) extract($_POST);
?>
on the the top of your php pages.


ryanwray at gmail dot com
24-Nov-2004 04:03

In reply to ben at nullcreations dot net:

This is true of the super-global $_SESSION, as it will always be processed last (it is not considered in variables_order directive)

However, it is possible to over-write other data, namely GET, POST, COOKIE, ENVIROMENT and SERVER.

Of course, what you can overwrite will depend on the directive variables_order - by default, you could overwrite GET and POST data via COOKIE (because cookie data is processed last out of the three which should not really be of great concern.

My below code is irrelevant unless extract or another method which does the same thing (ie. I have seen variable variables used before to reach the same affect) is used.


ben at nullcreations dot net
23-Nov-2004 01:53

Just a note to all the people who think $_SESSION can be poisoned by register_globals - it can't.

Consider the fact that GET/POST/COOKIE is Processed *before* sessions are.  This means that even if you have register_globals on, and they write to $_SESSION, $_SESSION will just get reset again with the appropriate values.

Some people take to using extract() as a means to simulate register_globals in scripts where they're not sure what the server environment will be - this is when you should worry about such things.  The reason is because extract() can concievably occur after GET/POST/COOKIE and SESSION processing.


snarkles <anything at $myname dot net>
19-May-2004 09:06

If you're under an Apache environment that has this option enabled, but you're on shared hosting so have no access to php.ini, you can unset this value for your own site by placing the following in an .htaccess file in the root:

php_flag register_globals 0

The ini_set() function actually accomplishes nothing here, since the variables will have already been created by the time the script processes the ini file change.

And since this is the security chapter, just as a side note, another thing that's helpful to put into your .htaccess is:

<Files ".ht*">
deny from all
</Files>

That way no one can load .htaccess in their browser and have a peek at its contents.

Sorry, not aware of a similar workaround for IIS. :\


dav at thedevelopersalliance dot com
18-Dec-2003 07:38

import_request_variables() has a good solution to part of this problem - add a prefix to all imported variables, thus almost eliminating the factor of overriding internal variables through requests. you should still check data, but adding a prefix to imports is a start.


 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt