在 PHP 中解决数学问题/表达式(字符串)
用户可以输入数学问题(表达式),例如 5 + 654
、6 ^ 24
、2!
、sqrt(543)
、log(54)
、sin 5
、sin(50)
。经过一些重新格式化(例如将 sin 5
更改为 sin(5)
)并进行评估后,PHP 给出了正确的结果:
$problem = "5 + 5324";
eval("$result = " . $problem);
echo $problem . " = " . $result;
但是,这是非常不安全的:
/* 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;
任何人都可以吗?为我指明解析和解决数学问题(如上面的示例)的正确方向,这安全吗?谢谢。
顺便说一句,eval
不就是 evil
的常见拼写错误吗?
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.
Btw, isn't eval
just a common misspelling of evil
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
理想情况下,我认为您必须创建某种语法解析器/词法分析器引擎,可以将公式解析为各个部分,然后对其运行方程式。
这样,任何恶意函数都会被忽略,并且系统可能会返回错误。
Ideally, I think you would have to create some sort of grammar parser/lexer engine that could parse out the formula into its parts and then run the equation on that.
That way any rogue functions would just be ignored, and the system could return an error.
看看 PHPExcel 中的计算引擎...它实现了一个安全的公式解析器,可以处理大多数可以计算的公式表达式(包括 LOG() 等函数,以及 2^3 作为幂而不是二元运算符)由 Excel 本身。
Take a look at the calculation engine in PHPExcel... it implements a safe formula parser that can handle most formulaic expressions (including functions such as LOG(), and 2^3 as a power rather than a binary operator) that can be calculated by Excel itself.
好吧,在这种情况下,你几乎需要实现自己的计算器 - 我在一次工作面试中得到了它,所以这是我的代码。请记住,这对我来说确实是遗留下来的东西,但我认为它可能会给你一些想法:
另外,我在检查中写了它,对于奇怪的评论感到抱歉。
Well you pretty much need to implement your own calculator in that case - I got it at a job interview once so here is my code. Remember it's really legacy stuff for me but I figured it might give you some ideas:
Also I wrote it in check so sorry for weird comments.