Search code examples
phphtmlkohana

How do I create an editable PHP/HTML template without security risk?


Using a Kohana View class, I want admin users to be able to edit HTML templates and the easiest way to do this is to let them edit the template file directly i.e. load it in a textarea and save file on submit.

But a malicious user could potentially write php code inside this textarea and call static functions that may cause malicious behaviour. How can I restrict PHP to only evaluate simple variables in this editable template and disallow function calls and other types of logic?

Example: view/template.php

Hey $firstname,

Best regards,
$admin

Solution

  • Don't parse the php. Read it into a string using file_get_contents and do a str_replace with a list of known variables.

    e.g.

    $replace = array(
        '$firstname' => $firstname,
        '$admin' => $admin
    );
    $template = file_get_contents('view/template.php');
    $template = str_replace(array_keys($replace), array_values($replace), $template);
    

    This obviously gets more complicated if you want to let them do anything more advanced than your example, but that's what things like smarty are for.