I’m wondering what sorts of things should be checked when using eval() in PHP to parse a formula that is entered by a user filling out a form. I’ve seen lots of answers about eval(), but not all of them seem to agree.
Here’s what I’ve gathered:
- Don’t use eval for strings (this could be a problem, since it is a formula I need to parse)
- Strip the input coming from the form (I’m not entirely sure what things I need to strip)
- 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 folks think I should do?
EDIT: I tried the eval method, and while it does work, the sanitation I used did not support more than two operands. Since I really don’t feel like writing my own (possibly insecure) sanitation regex, I’m just going to find and use a pre-written math class instead. Thanks to everyone for the suggestions!
If you must use
eval, theevaldocs page on it has some code that will allow you to filter mathematical formulas. But as others, and the PHP docs page, have said, it’s not a good idea to useevalunless there is no other alternative.