phpmatheval

Process mathematical equations in php


A user is allowed to enter any mathematical equation they like (with one variable):

x + 5

1 - x/2

(x/3) * (56/13)

These are stored as strings in the database. When they are retrieved I need to substitute 'x' for a number and check the value of the equation.

How could I do this?

I was considering writing a parser to deconstruct the strings and turn them into equations, however this sounds expensive and problematic. The other option is to pass them through eval (but I'm not a great fan of using eval if I can help it).

Any ideas?

UPDATE: I also need to be able to get the boolean value of something like "(x > 5)". This is not possible with evalMath

UPDATE 2: I need to fire lots of these a second. I've been looking into eval in php but cant get it to return a boolean for (5 > 4) however I noticed js would do it... maybe I should investigate node.js...

UPDATE 3: After having some fun trying out node.js (and getting it to work) I went back and got eval to work in PHP see: Can php eval return a boolean value?

So I will go with eval with a very very hardcore filter on user input.


Solution

  • Eval is not Evil!!!!!

    Yes it can stuff your system up completely if you write bad code - but recent PHP versions can parse an invalid expression without crashing the whole script. And there are many other ways of exposing your system by writing bad code.

    That just leaves the possiblity of code injection attacks - which can easily be avoided by doing a preg_replace on everythnig which is not a safe character (i.e. 0....9, (, ), +, -, *, /, ^, .)