The safest way to use eval to parse equations entered by a form

I am wondering what things should be checked when using eval () in PHP to parse the formula entered by the user filling out the form. I saw a lot of answers about eval (), but not all of them seem to agree.

Here is what I put together:

  • Do not use eval for strings (this may be a problem, as this is the formula I need to parse)
  • Reset the input coming from the form (I'm not quite sure what I need to remove)
  • Eval may or may not be evil and is a security risk (are there alternatives for parsing an equation in a string?)

What do you think I should do?

EDIT: I tried the eval method, and although it works, the sanitation I used did not support more than two operands. Since I really don’t want to write my own (possibly unsafe) sanitation solution, I'm just going to find and use a pre-written math class. Thanks everyone for the suggestions!

+4
source share
3 answers

If you must use eval , there is code on the eval docs page that allows you to filter math formulas. However, like the others, and the PHP docs page, they said it was not recommended to use eval unless there was another alternative.

 <?php $test = '2+3*pi'; // Remove whitespaces $test = preg_replace('/\s+/', '', $test); $number = '(?:\d+(?:[,.]\d+)?|pi|Ο€)'; // What is a number $functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions $operators = '[+\/*\^%-]'; // Allowed math operators $regexp = '/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?2))?)+$/'; // Final regexp, heavily using recursive patterns if (preg_match($regexp, $q)) { $test = preg_replace('!pi|Ο€!', 'pi()', $test); // Replace pi with pi function eval('$result = '.$test.';'); } else { $result = false; } ?> 
+3
source

Using EVAL for user input is a great way to get your server hacked. Do not do this.

A valid method is to parse an expression, so you understand each element of it and then evaluate the expression that you analyzed. For mathematical expressions, you can find a reliable package that does just that.

+4
source

eval always dangerous. Once you start the blacklist (filtering), people will find ways to get around the assumptions you make in your filter logic. Correct white list expressions are a safer way.

But the most effective way to protect yourself from someone abusing functionality is to probably write the right parser for mathematical expressions. If the formulas that you would like to support are not too complicated, this is not even that part of the deal if you use a simple approach with a batch of recursive descent down. There are some links in this answer to get you started. There's also this article that develops a recursive descent parser for a simple calculator (unfortunately, this is in Java, though).

0
source

All Articles