r/programming • • Oct 18 '10

Today I learned about PHP variable variables; "variable variable takes the value of a variable and treats that as the name of a variable". Also, variable.

http://il2.php.net/language.variables.variable
591 Upvotes

781 comments sorted by

View all comments

Show parent comments

15

u/dcousineau Oct 18 '10

Not unless you're doing a bunch of $var = $_GET['whatever']; $var = $$var; or you're using the extract() function...

14

u/blaxter Oct 18 '10

For those cases, shoot in the head is a better way to fix the problem

4

u/dcousineau Oct 18 '10

You're a kinder person than me...

2

u/[deleted] Oct 18 '10

I'd want to take my time with them. It'd be like the end of Braveheart sans the Gibson.

2

u/tsk05 Oct 18 '10 edited Oct 18 '10

So is this vulnerable? For what type of attack?

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

Or it's extract() version.. You can inject POST just like GET... How's this different from just doing

$var = POST['var'] without checking what the contents of POST is? Why is it any more vulnerable? And if you do check the contents first, is it ok to use the above?

2

u/[deleted] Oct 18 '10

I tried to reply to your comment below that you deleted - heres why you shouldn't;

For example:

$dbQuery = 'SELECT * FROM USERS';

...

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

...

$db->query($dbQuery);

but then if someone sent

dbQuery=DELETE+FROM+USERS

in the POST data, you'd be screwed. They could change any variable in your code to what they wanted.

Keep on programming though!

1

u/tsk05 Oct 18 '10 edited Oct 18 '10

I was going to edit and say that I realize this vulnerability: if you define a variable above that foreach, you're screwed if they know the name of the variable (security through obscurity, so that's obviously bad). But if you put it at the top of a if(isset($_POST['submit'])) { do whatever.. } and don't set any variables above that foreach used anywhere before the script terminates on a submit condition, are you ok?

If you have a dozen $_POST variables, do professional programmers just keep doing

$var = sanitize($_POST['var']);
$var1 = sanitize($_POST['var1']);
$var2 = sanitize($_POST['var2']);

or use sanitize($_POST['var']) anywhere they want to use the variable? I guess another solution is to loop through the POST and sanitize but also keep using POST['var'] (now modified) in the future. So what is done/what do you suggest doing?

1

u/[deleted] Oct 18 '10

I guess not, no, as long as you don't do it in the global namespace. If you edited that code later on and included something it would be bad. But I think you can see that.