0

Using the code found here I am posting input fields to a php script. The result looks something like this

 data:{
"textfield": ["",""],
"dropdown": ["option1","option1"],
"siteTitle":"this is the site title",
"siteKey":"",
"siteurl":"",
"address1":"",
"address2":"",
"address3":"",
"landline":"",
"method":"addSite",
"small-input":"",
"medium-input":"",
"large-input":""
}

I am picking off each field using the following.

 $data = $_POST['data'];
 $data =stripslashes($data);
 $obj = json_decode($data); 
 $siteTitle = sanitize($obj->siteTitle);
 if (!$siteTitle){echo json_encode(array("msg"=> "Site title missing"));break;}

Is there a way in php to automatically step thru each posted field and assign it to a variable based on the name ?

for those concerned about Déjà vu, don't be.

Community
  • 1
  • 1
maxum
  • 2,825
  • 4
  • 33
  • 49
  • You're basically asking for a slightly different version of [`register_globals`](http://php.net/manual/en/security.globals.php) which is a rather significant security risk. I'd suggest not going that route. – Amber Oct 15 '11 at 03:26

2 Answers2

1
$obj = json_decode($data);
foreach($obj as $key => $val)
{
    $$key = $val;
}
var_dump($method); // 'addSite'
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
0

You could do this:

$array = json_decode($json, true);
extract($array);

but let me STRONGLY encourage you to NOT do this. It's extremely lazy programming, leaves your script open to variable injection attacks, and basically tries to recreate the horribly stupid moronically bad times of PHP in its "register_global defaults to on" days of infamy.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Yes, this was my thinking also. So really this was an ethics question as much as technical one. But I can't see the vulnerability as I am requesting the variable and sanitizing it as opposed the variable just becoming available. – maxum Oct 15 '11 at 10:03
  • Nothing says a malicious user can't fake a post to your form and submit `_SESSION[issuperuser]=1` type thing. Unless you're manually specifying each variable you want to be auto-created in this manner, and just loop over every var submitted, ANYTHING can be injected into your script. This is why register_globals was/is/always will be such a moronic idea. – Marc B Oct 15 '11 at 21:42