tags:

views:

35

answers:

1

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;

    }

This effectively renders all the code by replacing the variables with their correct content.

A: 

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.

Jonathan Kuhn
I'd tried some things along that line, but it didn't seem to work -> mainly because the Controller would assign a result to a variable in the template component - it was getting it to actually evaluate the result at run time that caused the issue. The code I added in my edit, effectively renders the dynamic variables. I'm still not so sure this would be any safer than eval though without correctly sanitising anything that comes from user input stored in the database.
niggles