Solving a math problem/expression, which is a string, in PHP
- by Koning WWWWWWWWWWWWWWWWWWWWWWW
The user can enter a math problem (expression) like 5 + 654, 6 ^ 24, 2!, sqrt(543), log(54), sin 5, sin(50). After some reformatting (e.g. change sin 5 into sin(5)), and doing an eval, PHP gives me the right result:
$problem = "5 + 5324";
eval("$result = " . $problem);
echo $problem . " = " . $result;
However, this is quite unsafe:
/* If you read this, please, plz don't be stupid and DO NOT EXECUTE this code!!!!! */
$problem = "shell_exec('rm -rf /')";
eval("$result = " . $problem); /* Nukes system */
echo $problem . " = " . $result;
Can anyone point me in the right direction parsing and solving a math question like the examples above, which is safe? Thanks.