编辑: 所有人都提出了很好的观点,专用的模板语言显然是最好的方法。谢谢!
我写了这个快速类来通过PHP进行模板设计 - 我想知道如果我将模板设计开放给用户是否容易被利用(目前没有立即计划,但考虑未来可能出现的情况)。
class Template {
private $allowed_methods = array(
'if',
'switch',
'foreach',
'for',
'while'
);
private function secure_code($template_code) {
$php_section_pattern = '/\<\?(.*?)\?\>/';
$php_method_pattern = '/([a-zA-Z0-9_]+)[\s]*\(/';
preg_match_all($php_section_pattern, $template_code, $matches);
foreach (array_unique($matches[1]) as $index => $code_chunk) {
preg_match_all($php_method_pattern, $code_chunk, $sub_matches);
$code_allowed = true;
foreach ($sub_matches[1] as $method_name) {
if (!in_array($method_name, $this->allowed_methods)) {
$code_allowed = false;
break;
}
}
if (!$code_allowed) {
$template_code = str_replace($matches[0][$index], '', $template_code);
}
}
return $template_code;
}
public function render($template_code, $params) {
extract($params);
ob_start();
eval('?>'.$this->secure_code($template_code).'<?php ');
$result = ob_get_contents();
ob_end_clean();
return $result;
}
}
示例用法:
$template_code = '<?= $title ?><? foreach ($photos as $photo): ?><img src="<?= $photo ?>"><? endforeach ?>';
$params = array('title' => 'My Title', 'photos' => array('img1.jpg', 'img2.jpg'));
$template = new Template;
echo $template->render($template_code, $params);
这里的想法是将模板(PHP代码)存储在数据库中,然后通过使用正则表达式的类运行它,以仅允许允许的方法(if,for等)。有人看到利用漏洞并运行任意PHP的明显方法吗?如果有的话,我可能会采用更标准的模板语言,比如Smarty...