Page 1 of 1

automatic handling of the $_POST array

Posted: Mon Sep 26, 2005 11:51 pm
by fgomez
Hello,

I'm not exactly new to PHP, but I'm new enough to ask a stupid question. :roll:

I searched around for quite a while trying to figure this out, but either didn't find it or didn't know it when I saw it. Basically, I'm lazy and want the $_POST array to handle itself; I don't want to type out "$fieldName = $_POST['fieldName'] ; " one million times.

I figure the way to start is something like this:

Code: Select all

foreach ($_POST as $key => $value) {
	$key = "usr_" . $key ;
		// I like for variables the user entered to be called $usr_whatever -- personal preference, I guess
	$value = trim(stripslashes($value)) ;
	// And here's where I don't know what to do next.
	}
Thanks. Should be an easy one.

Posted: Tue Sep 27, 2005 12:03 am
by feyd
$$key

it's called variable variables.
http://php.net/language.variables.variable

Posted: Tue Sep 27, 2005 1:25 am
by McGruff
There's also the extract() fn.

BUT... auto-declaring vars from a superglobal is just as bad as register globals on - in some ways worse. What it means is that, with a forged form, a hacker can set any variable with any value in the same scope as the foreach/extract lines.

Register globals only lets them do that in the global scope. Also, vars created by register globals on will immediately be overwritten by your own code, if you declare them before they are first referred to. Only undefined vars in the global scope are vulnerable.

With foreach auto-extracting, they can overide anything in the same scope as the extract code, undefined or not. If you declare the var yourself afterwards, you're safe. If it was declared previously, you're not.

In order for this to be useful to the attacker they have to know or guess the name of one of your vars. If you prefix var names, as you have done, that gives you some protection - provided of course you don't have something else prefixed with "user".

Posted: Thu Sep 29, 2005 7:57 pm
by fgomez
Thank you both!