PHP 作为存储在 Mysql 中的模板引擎 - 白名单函数
虽然我已经阅读了无数关于使用 PHP 作为模板引擎(使用输出缓冲)的文章,但我仍在尝试为其提供理由。
因为我想知道是否可以使用 PHP 作为 Web 应用程序的模板引擎(用户将能够自己更改布局)——我仍然没有找到有关以下内容的任何信息:
- 将模板存储在 MYSQL 数据库中
- 评估它们
- ,但只包括列入白名单的函数(让它们只能访问一组有限的函数——while、foreach等……)
有人在寻找相同的解决方案,但可以提供更多信息吗?那太好了。
While I have been reading through countless posts about using PHP as a template engine (using output buffering), I'm still trying to make a case for it.
As I'm wondering if I could use PHP as a template engine for a web app (users will be able to change the layout themselves) -- I still don't find any info regarding the following:
- Store the templates in a MYSQL database
- Eval them
- BUT only include functions that are whitelisted (to give them only access to a limited set of functions -- while, foreach, etc ...)
Anybody looking for the same solution, but can chime in with a bit more information? That would be quite nice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不能信任编辑模板的用户,那么最好使用单独的模板语言。
请注意,许多模板语言(例如 Smarty)也提供代码执行功能。您可能需要在引擎的配置中禁用这些功能。
禁用 PHP 中所有潜在危险的函数是一项非常艰巨的任务,而且很容易搞砸。请参阅可利用的 PHP 函数
If you can't trust the user editing the template, you are better off using a separate templating language.
Note that many template languages like Smarty provide code execution functions as well. You may need to disable those in the engine's configuration.
Disabling all potentially dangerous functions in PHP is a very arduous task, and easy to screw up. See Exploitable PHP functions
PHP 不适合作为模板引擎来满足您的目的。您应该使用具有沙箱支持的正确模板引擎:Twig。
PHP is not suitable as a template engine for your purpose. You should use a proper template engine with sandboxing support for that: Twig.
这可能是一项相当困难(但很有趣,如果您感兴趣的话)的任务,因为它涉及构建一个小型 PHP 解析器,它可以完美地识别任何函数调用或方法调用(因为如果您错过了一个,那么您就完蛋了/ hacked/...),然后检查所有匹配的函数标识符令牌是否都在白名单中,否则拒绝评估。为了生成解析器,您可能需要查看PHP_ParserGenerator,不幸的是它似乎不是不再维护,或lemonPHP/JLexPHP,这可能是最新的,但您需要使用 Java 来生成解析器。
由于所有这些都是一项相当繁琐的任务,因此大多数人求助于使用自定义(虚构的)模板语言,该语言类似于 PHP,但并不完全相同。
流行的 PHP 模板引擎包括:
更多内容请参见此处 和此处< /a>
That is probably a quite difficult (but interesting, if you are into the topic) task, because it involves building a small PHP parser, which can flawlessly identify any function call or method call (because if you miss one, you're screwed/hacked/...) and then check if all your matched function identifier tokens are in your whitelist, and otherwise deny eval-ing. For generating your Parser, you might want to check out the PHP_ParserGenerator, which unfortunately does not seem to be maintained anymore, or lemonPHP/JLexPHP, which may be more up to date, but you need to use Java to generate the Parser.
Because of all this is a quite tedious task, most people resort to using a custom (made-up) template language, which is similar to PHP, but not identical.
Popular PHP template engines are, among others:
More can be found here and here