A little while ago, I wrote a tutorial about how important it is to sanitize PHP user input strings. Not only is it important to sanitize user input being fed into a database query, but it's also important to sanitize user input being displayed to the end-user to generate valid HTML: For example, converting &
to &
. Otherwise, you can end up with javascript injection attacks and that sort of thing. This happens when a malicious user fills out a user field with javascript, for example, it isn't properly sanitized, and it's displayed on a webpage where a different victim user's web browser sees it and it executes the malicious javascript.
To combat this, I rolled my own template library for DaniWeb, which is built on top of the Codeigniter 3.1.x PHP framework. By default, Codeigniter, being an MVC framework, requires you to pass an array of variables into a view template that you want the template to have access to. My template library handles this by creating a class where you "assign" variables to a template. For each of those variables, it sanitizes them to make sure they aren't vulnerable to any injection bugs, and also runs them through a bad words censor. This makes it really easy to make sure that there are absolutely no injection bugs anywhere on DaniWeb, as templates literally only have access to variables that have been passed through the filter.
Here's an example of how I would access my template library from a controller:
$this->dw_template->assign('name', $name);
$this->load->view('hello', $this->dw_template->get());
Then, from within the hello.php template, I would be able to do something like:
<p>Hello, <?= $name ?>!</p>
This ensures that there's never any logic within the templates, and every variable they have access to is guaranteed to be sanitized.
Alternatively, if there's a specific variable I want to pass into the template but I don't want to sanitize it for any particular reason, I can pass in the 'true' parameter, as so:
$this->dw_template->assign('unsanitized_variable', $unsanitized, true);
I tend to use this in my own code when the variable is something like a number, where I know beyond a reasonable doubt that there is nothing to sanitize, so I want to save it from being passed into the sanitization functions for efficiency sake.
The code for the deep_clone()
function that I used is here.