Can someone please explain

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Wootah
Forum Newbie
Posts: 13
Joined: Wed Jul 14, 2010 7:08 pm

Can someone please explain

Post 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?
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Can someone please explain

Post 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.
Wootah
Forum Newbie
Posts: 13
Joined: Wed Jul 14, 2010 7:08 pm

Re: Can someone please explain

Post by Wootah »

thanks.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Can someone please explain

Post 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.)
Post Reply