gpt4 book ai didi

php - 使用 PHP 作为模板语言

转载 作者:可可西里 更新时间:2023-10-31 23:59:40 24 4
gpt4 key购买 nike

编辑: 各个方面都很棒,专用模板语言显然是必经之路。谢谢!

我写了这个快速类来通过 PHP 进行模板制作——我想知道如果我曾经向用户开放模板制作(不是近期计划,而是考虑 future ),这是否容易被利用。

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...

最佳答案

当然..

$template_code = '<?= `rm -rf *`; ?>';

编辑:

暂时想不出别的了。但是你应该知道你的范围受到损害,如果在同一个Template上多次调用渲染实例。

例如,如果您 render('<?php $this->allowed_methods[] = "eval"; ?>') .. 然后是 Template 的实例会有eval作为下一个渲染的可接受函数.. ;)

关于php - 使用 PHP 作为模板语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2770606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com