评估字符串作为条件PHP [英] Evaluate string as condition PHP

查看:62
本文介绍了评估字符串作为条件PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义验证规则模块,该模块实质上允许用户设置CSV验证。我的问题是我将它放入此数组:

I have a custom validation rule module that essentially allows users to set up CSV validation. My problem is I get it to this array:

Array(
    [field_name] => 'is_int(324230435)',
    [some_other_field] => 'strlen("some str") > 25'
)

我做了一些研究,遇到了 eval()函数。

I did some research and came across the eval() function.

裁判:如何在PHP的IF条件下使用字符串

但是,由于安全问题,我真的不想使用 eval()(参考: 何时在php中出现邪恶?

However, I really don't want to use eval() due to the security issues (ref: When is eval evil in php?)

尽管没有严格说出eval是邪恶的,但我仍然希望有替代方法。

Although it doesn't strictly say eval is evil, I still would prefer if there was an alternative method.

我过于谨慎关于 eval()的用法-也许我应该逃避使用 eval()还是有更好的方法?

Am I being over-cautious about the usage of eval() - perhaps I should escape and use eval() or is there a better way?

推荐答案

执行任意字符串作为代码会发出警告,无论您采用哪种方式,都执行任意代码 eval 没有其他更好的选择,它可以让您执行PHP代码而无需…执行PHP代码。

Well, executing arbitrary strings as code has the caveat that you're executing arbitrary code whichever way you do it. There's no better alternative to eval that would let you execute PHP code without… executing PHP code.

理智的方法要在此处定义的是 DSL ,它为您的用户提供了一种编写某些受限内容的方法不是PHP代码的表达式 ,您将使用特定的有限功能对其进行解析和评估。

The sane way to go here is to define a DSL which gives your users a way to write certain limited expressions which are not PHP code, which you will parse and evaluate with specific limited capabilities.

一个好的库可以做到 Symfony的ExpressionLanguage组件。除此之外,您还将进入语言解析器的领域。

A good library which does that is Symfony's ExpressionLanguage component. Beyond that you'd go into the domain of language parsers.

这篇关于评估字符串作为条件PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆