开发者

How can I output this dynamic data without eval?

I've been writing a CMS in MVC style and have used a Template class to pull in the various files required via file_get_contents

At the end I do

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

Knowing that eval is evil, how can I alternatively flush this data so the PHP actually renders the code?

At the moment the Template class does this once everything's been loaded. Is it possible for the Template class to return this code to my index.php as a variable and then run something to make it execute?

Every example of coding an MVC style site I've come across uses eval to solve the problem.

An additional related question - I understand eval can be used to run malicious user-inputted code, but wouldn't some other function suffer the same fate? If I turn any user content into html entities, wouldn't this overcome this?


Quite possibly my method is flawed, but it follows the examples I've been reading, which is why I'm keen to see another method that avoids eval.

I did just find this snippet which achieves the same thing:

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

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

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

    }

Thi开发者_如何学JAVAs effectively renders all the code by replacing the variables with their correct content.


in my templates I use output buffering to capture a script that is included. the included code is run just like any other included file. pseudo: start buffer, include file, capture buffer, erase buffer. here is a short example:

//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();

After that runs, $template_output would have anything output by the included file after it has run any code inside. This allows me to use loops and vars and such when processing a 'view'.

Please note though, this is used on my personal site where I am the only one making changes to the template files. I do not allow anyone else to edit the template files as that would be ridiculously dumb.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜