vote up 1 vote down star

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!

flag
2  
You should reconsider your design. At the very least, consider using JSON instead of asking the user to type in PHP. – Anon. 2 days ago

5 Answers

vote up 0 vote down

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.

link|flag
vote up 0 vote down
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;
  }
}
link|flag
vote up 0 vote down

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"
link|flag
2  
"If eval is your answer, you're asking the wrong question." ~ Rasmus Lerdorf, I think – robertbasic 2 days ago
vote up 0 vote down

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.

link|flag
vote up 0 vote down

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 :)

link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.