开发者

Safely convert user-provided array string into PHP array?

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 strin开发者_开发百科g $_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!


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


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.


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;
  }
}


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"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜