Take the 2-minute tour ×

My understanding is that all variables should be output through htmlspecialchars() in a view.

Are there any approaches or methods to do this, without having to specify the function on each appropriate line in each view?

The best that I could come up with is to have a helper function as follows: function html_escape($var)

function h($var)
  if (is_array($var))
    return array_map('h', $var);
    return htmlspecialchars($var, ENT_QUOTES, 'UTF8');

But still...this could get very tedious!

Any ideas?

share|improve this question
who says htmlspecialchars should be used for every variable output? –  imm Oct 18 '11 at 22:08
This is one the reasons why PHP templating engines exist. Check this tutorial for some info. –  Michael Mior Oct 18 '11 at 22:09
@imm Well, I mean to say for every user-provided variable –  JonoB Oct 18 '11 at 23:40
@Michael Mior - Thanks - nice article! –  JonoB Oct 18 '11 at 23:40

3 Answers 3

up vote 2 down vote accepted

You may have the function h() output the escaped data, rather than return it. Therefore, instead of writing <?php echo h($myvar); ?> you may write <?php h($myvar); ?>. This is now two characters shorter than echoing the variable without converting to entities.

share|improve this answer

It's an important distinction to note that not all variables must be run through htmlentities/htmlspecialchars, just ones that contain user-supplied content in anyway, that are not already filtered against a rule-set to prevent arbitrary code inclusion.

You could create a helper function to cut down on the typing slightly, or loop all user-supplied input through htmlentities/htmlspecialchars in your controllers before handing them off to the view (though, this will likely be less efficient since it is unlikely every piece of user-supplied input will be displayed)

share|improve this answer

What you have there is probably the closest you come to an easy escape in allot of situations.

Personally i use a little loop on my variables, if i know i'm going to be using any $_GET variables in my html output, i run this:

  $_GET[$key] = htmlspecialchars($value);

Then start my html tags right after.

Not everything needs to be escaped though, unless the user have any influence on it.

In addition, you could have a script called escape.php, which uses the above method on common variables you use, like $_GET, $_POST, $_COOKIE and so on, then include('escape.php') it in your scripts before use in the html output.

All over it pretty much depends on your taste and what you need for your project.

share|improve this answer

Your Answer


