0

In my frontend I have someone who can change a formula in a form field.

The formula will be saved in a mysql database (text field right now).

For example this: "4 + (5 + 2 ) ^ (6 * 10)".

Now I want to solve this in my php code. My Problem is there I need the function "pow" for example.

Is there any good solution to handle all or most math functions for php. Or do I have to manipulate the "^" to pow(4 + (5 + 2), (6 * 10)).

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3553562
  • 119
  • 1
  • 8

1 Answers1

0

There are at least two solutions: either use the eval function which I don't recommend for security reasons (easiest way to achieve your goal), or use any expression library (like Symfony's Expression Language).

While the former would be the fastest way, I would recommend the latter. There's a lot of flexibility you can achieve by exposing functions you only need or writing custom ones.

Mike Doe
  • 16,349
  • 11
  • 65
  • 88
  • PHP's function token_get_all() allows you to get some security going for the eval function and only allow T_OPEN_TAG T,_LNUMBER, T_WHITESPACE and T_CLOSE_TAG as valid token_names... demo with safe code http://rextester.com/FMGQ6654 .. demo with "unsafe" code because trying to set a variable http://rextester.com/YALT96831 – Raymond Nijland Feb 04 '18 at 12:59