【问题标题】:How can I output this dynamic data without eval?如何在没有 eval 的情况下输出此动态数据?
【发布时间】:2010-08-12 23:25:44
【问题描述】:

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

最后我做到了

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

知道 eval 是邪恶的,我该如何选择刷新这些数据以便 PHP 实际呈现代码?

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

我遇到的每个编写 MVC 样式网站的示例都使用 eval 来解决问题。

另一个相关问题 - 我知道 eval 可用于运行恶意用户输入的代码,但其他一些函数不会遭受同样的命运吗?如果我将任何用户内容转换为 html 实体,这不会克服这个问题吗?


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

我刚刚发现这个 sn-p 实现了同样的事情:

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

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

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

    }

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

【问题讨论】:

  • 也许你的设计有缺陷。如果您简洁地解释您要解决的问题,那么也许可以通过更改来避免 eval。
  • 我同意 James 的观点,不仅不清楚你在做什么,还不清楚你为什么这样做。
  • 您可能对这里的一些对话感兴趣 - stackoverflow.com/questions/3326446/…

标签: php eval


【解决方案1】:

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

//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 将在包含文件中运行任何代码后输出任何内容。这允许我在处理“视图”时使用循环和变量等。

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

【讨论】:

  • 我尝试了一些类似的方法,但它似乎不起作用 -> 主要是因为控制器会将结果分配给模板组件中的变量 - 它实际上是在运行时评估导致问题的结果。我在编辑中添加的代码有效地呈现了动态变量。我仍然不确定这会比 eval 更安全,尽管没有正确清理来自存储在数据库中的用户输入的任何内容。
猜你喜欢
  • 2022-01-27
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 2014-06-06
  • 1970-01-01
相关资源
最近更新 更多