Solving a math problem/expression, which is a string, in PHP

Posted by Koning WWWWWWWWWWWWWWWWWWWWWWW on Stack Overflow See other posts from Stack Overflow or by Koning WWWWWWWWWWWWWWWWWWWWWWW
Published on 2010-05-15T18:42:43Z Indexed on 2010/05/15 18:54 UTC
Read the original article Hit count: 327

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about php

Related posts about math