Safely execute a string of PHP code?

I am looking for the safest way to execute a string of PHP code.

I believe this can be done with the eval() function.

In context; A user submits a form field which contains a block of PHP code, for example, an array:

array('a' => 1, 'b' => 2);

This would be submit as a string

$_POST['code'] = "array('a' => 1, 'b' => 2);";

If I wanted to convert this to json I could do something like.

$returnValue = '';
eval("\$returnValue = json_encode($_POST['code']);");
return $returnValue;

This should output {"a":1,"b":2}

I believe there are great security risks with this? Is there a safer way to do it?

tl;dr: Code is sent via form, evaluated and the typical output is returned.


using eval() gives somebody full access to your sourcecode and the related data, that’s the maximum security risk you can get at this level. but in most cases that’s just not necessarry, your eample is insufficient for eval.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.