PHP as template engine stored in Mysql - Whitelist Functions
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.
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 is not suitable as a template engine for your purpose. You should use a proper template engine with sandboxing support for that: Twig.
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:
- Smarty
- Twig
- PEAR Template Engine
- Savant
More can be found here and here
精彩评论