I am developing a web application in php, and have created a small framework tailored to my needs. A part of this framework is a templating engine, where I can feed a list of values into html templates.
In these templates, I rely heavily on constructs like
<?= $value ?>
where the convention is, that $value must not contain html tags that should be processed as such. With that, I thought I should be able to xss-proof my application by using
<?= htmlspecialchars($value) ?>
or
<?= htmlentities($value) ?>
wherever appropriate.
However, because I required that $value must not contain any html markup, I noticed that I could require every occurrence of to be escaped, without losing functionality.
Of course, just always calling 'htmlspecialchars' explicitly seems like a ridiculous amount of write overhead, and hence I wondered if there is a way to make this call implicit?
in such a way, that
<?= $value ?>
will always be equivalent to
<?= htmlspecialchars($value) ?>
Thanks.
Overwriting default php functionality may not be a good idea since sooner or later foreign code may enter your project that does not conform to your chances.
I would go another way and add the call to htmltentities
as default function of your templating engine. How do you assign variables to it? For example, I once wrote a small template engine that basically used this->view->assign('name',$var)
calls to pass variables to templates and did the escaping in the part of the code before my assigned variables where processed (you could also add a method $this->view->assignRaw(...)
which really passes raw content without escaping.
Of course, if you pass arrays you will have to work on them recursiveley, also handling the keys. If you pass objects, everything might even get more difficult, since you might not really want to automatically replace values here and cloning them beforehand might get expensive. You still have to be aware of what you are passing into your templates but it saves you from the most common mistakes. Maybe you should have a look how modern template engines like Smarty3 or Twig solve these kind of problems.