automatic handling of the $_POST array

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
fgomez
Forum Commoner
Posts: 61
Joined: Mon Sep 26, 2005 11:23 pm
Location: Washington, DC

automatic handling of the $_POST array

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

$$key

it's called variable variables.
http://php.net/language.variables.variable
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post 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".
fgomez
Forum Commoner
Posts: 61
Joined: Mon Sep 26, 2005 11:23 pm
Location: Washington, DC

Post by fgomez »

Thank you both!
Post Reply