Page 1 of 1

Can someone please explain

Posted: Mon Sep 06, 2010 6:28 pm
by Wootah
I am looking at some code written by someone else and this is the code snippet. :

Code: Select all

extract($_POST);
		
if($email && $database) 
{
}
And here is part of the html:

<td height="30" align="left" valign="middle"><input name="email" type="text" class="imput" /></td>
<td height="30" align="left" valign="middle"><input name="database" type="text" class="imput" /></td>

Now the two variables $email and $database do not exist anywhere in the code until the part I've highlighted. So what I think is happening is the the extract($_POST) is getting the form fields email and database and putting the values from the $_POST into the variables without a need to explicitly assign them?

From the extract function there is this example:
http://php.net/manual/en/function.extract.php

Code: Select all

$size = "large";
$var_array = array("color" => "blue",
                   "size"  => "medium",
                   "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size\n";
It seems to extract and create variables that are echoed...

Is this just a welcome to the magic of php issue that I should just accept and be grateful for?

Re: Can someone please explain

Posted: Mon Sep 06, 2010 7:11 pm
by JakeJ
The extract() function will take an array and extract the key/value pairs as variable name/value. So yes, this is just part of the magic of php.

I always prefer to do this manually but I guess it's because I feel like I have more control. Also, I sanitize my form fields when they are assigned to a variable.

Re: Can someone please explain

Posted: Sun Sep 12, 2010 7:29 pm
by Wootah
thanks.

Re: Can someone please explain

Posted: Sun Sep 12, 2010 7:49 pm
by requinix
extract() will get everything - even the stuff in $_POST that you don't want. Example:

Code: Select all

<?php

include "include/authenticateuser.php";
if (!$authuser) {
    header("Location: /login.php");
    exit;
}

extract($_POST);
if ($email && $database) {
    $query = "UPDATE `users` SET `email` = '{$email}' WHERE `database` = '{$database}' AND `user` = {$authuser}";
    // run query
} else {
    // form not filled out
}
If I edit the HTML form and put a hidden "authuser=1" then I can change the email address of anybody I want, regardless of who I'm logged in as. (And there's the opportunity for SQL injection, of course.)