代码之家  ›  专栏  ›  技术社区  ›  niggles

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

  •  1
  • niggles  · 技术社区  · 14 年前

    最后我会的

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

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

    我遇到的每一个编写MVC风格站点的例子都使用eval来解决这个问题。

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


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

    function interpolate( $string ){
            foreach ($GLOBALS as $name => $value){
    
                $string = str_replace( '$'.$name, $value, $string );
            }
    
            $string = preg_replace( '/[$]\\w+/', '', $string );
            return $string;
    
        }
    

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

    1 回复  |  直到 14 年前
        1
  •  0
  •   Jonathan Kuhn Reignier Julien    14 年前

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

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

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