tags:

views:

66

answers:

5

Users need to be able to enter a PHP array of parameters.

Currently, they see a text area where they are expected to enter PHP code that defines an array:

<textarea name="foo">
$bar = array( 'key' => 'value' );
</textarea>

I get the value of the text area as, for instance, the string $_GET['foo'].

How can I parse this so that I can use the array $bar? I'd rather not use eval if I can help it.

Thanks!

A: 

I'm not sure you don't want to use eval, since it is exactly for the purpose you are describing. However, since eval'ing user input is so dangerous, is that why you are trying to avoid it? If so, your only option will likely be to parse the value of $_GET['foo'], remove any dangerous or unwanted code, and then eval it.

[Edit] - New answer

Now that I think about it, if you need a simple solution for the user to input array-based data, look at parse_ini_string - http://us3.php.net/parse_ini_string. It will take a string in the following format and give you an associative array. You can even use multi-dimensional arrays if you need them.

one = 1
five = 5
animal = BIRD
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"
Renesis
"If eval is your answer, you're asking the wrong question." ~ Rasmus Lerdorf, I think
robertbasic
A: 

Oh freaky. Yeah steer clear of eval, that's asking for trouble. I'd probably just write a character-by-character parsing function to verify that the input is in the proper format, and then use php's string processing functions to get ahold of 'key' and 'value' and construct the array that way.

echo
A: 
if(is_set($_GET['foo'])) // we have something 
{
 // do your security testing and ad it to var $foos
 // now proceed 
  foreach($foos as $foo)
  {
   echo $foo;
  }
}
streetparade
A: 

Using parse_str() is the best option if you don't want to use eval():

$str = 'first=value&arr[]=foo+bar&arr[]=baz';

parse_str($str, $arr);

echo $arr['first'];  // value
echo $arr['arr'][0]; // foo bar
echo $arr['arr'][2]; // baz

The tokenizer functions might also be an option, but it'll be more complicated.

Alix Axel
A: 

If you absolutely must have the user define the array in this manner, you will be much better off by letting them define it as json. It's easy to convert and you dont have to lex it like the php code; much safer than eval. Plus, json is a lightweight and easy way to define arrays, so it will be a nicer user experience for them as well :)

devians
We had originally tried to use JSON, but liked the idea of not forcing users to learn a new syntax. Eval() is not very nice, though, so we're going back and making a javascript UI so building JSON arrays becomes more intuitive. Thanks for all of the answers, everyone!
Bacon