如何在没有eval的情况下输出此动态数据?

时间:2010-08-12 23:25:44

标签: php eval

我一直在用MVC风格编写CMS,并使用Template类通过file_get_contents提取所需的各种文件

最后我做了

eval('?>'.($template).'<?');

知道eval是邪恶的,我怎样才能刷新这些数据,以便PHP实际呈现代码?

目前,只要加载了所有内容,Template类就会执行此操作。 Template类是否可以将此代码作为变量返回到我的index.php,然后运行一些东西以使其执行?

我遇到的每个编码MVC风格网站的例子都使用eval来解决问题。

另一个相关的问题 - 我理解eval可以用来运行恶意的用户输入代码,但是其他功能不会遭受同样的命运吗?如果我将任何用户内容转换为html实体,这不会克服这个问题吗?


很可能我的方法存在缺陷,但它遵循我一直在阅读的例子,这就是为什么我渴望看到另一种避免eval的方法。

我刚刚发现这个片段实现了同样的目的:

function interpolate( $string ){
        foreach ($GLOBALS as $name => $value){

            $string = str_replace( '$'.$name, $value, $string );
        }

        $string = preg_replace( '/[$]\\w+/', '', $string );
        return $string;

    }

这有效地通过用正确的内容替换变量来呈现所有代码。

1 个答案:

答案 0 :(得分:0)

在我的模板中,我使用输出缓冲来捕获包含的脚本。包含的代码就像任何其他包含的文件一样运行。伪:启动缓冲区,包含文件,捕获缓冲区,擦除缓冲区。这是一个简短的例子:

//just the name of a template file to include.
$template = "someFile.tpl";
//start output buffering
ob_start();
//include the file. It has full access to all vars and runs
//code just like any other included script.
include($template);
//get anything output by the buffer during the include
$template_output = ob_get_contents();
//clean out the buffer because we already got the contents.
ob_end_clean();

运行之后,$template_output在运行任何代码后,包含的文件将输出任何内容。这允许我在处理“视图”时使用循环和变量等。

请注意,这是在我的个人网站上使用的,我是唯一一个对模板文件进行更改的人。我不允许任何其他人编辑模板文件,因为这将是非常愚蠢的。