Restrictions for PHP eval

2019-08-04 03:49发布

问题:

I have logical expressions that I need to evaluate. After some expresison template parametrized with its parameters, these expressions could look like this:

$expr1 = '1 or 0 and not(0 or 0)';
$expr2 = "'editor' == 'editor' and not(0 = 1) and 10 > 5";

So, I need to handle numbers, string literals, as well as logical and algebraical operators and round brackets between them.

When using PHP eval I also get undesirable unsecured abilities, like system function call, and so on.

So, is there any way to restrict PHP eval, or may be there is some better solution?

Thanks!

回答1:

You could use a tokenizer to check that the expressions don't contain function calls.

See the safer eval() class for an example.



回答2:

Ok, I got another solution. I've dawned that I can use PHP DOMXPath::evaluate to evaluate my logical expression. So, I got a working solution, which has no security issues. I think my problem is solved :)