1

Does preventing XSS really mean I have to run a htmlspecialchars() EVERY time I output some user input? For example, every time I display the users name? Seems really tedious.

Is there an easier way?

Andy Hin
  • 30,345
  • 42
  • 99
  • 142
  • Make a wrapper function with a shorter name to make it less tedious. (Also to avoid charset parameter.) Or use array_map+htmlescape on top of your templates. – mario Mar 10 '11 at 04:14
  • 1
    [Making Wrong Code Look Wrong](http://www.joelonsoftware.com/articles/Wrong.html) has an interesting discussion about this sort of thing and using prefixes on variable names to make sure you don't accidentally forget to run htmlspecialchars(). That said, doing anything manually is a drag - abstract it away! – chucksmash Mar 10 '11 at 04:19

3 Answers3

3

If you're worried about being the target of an attack, then you should always make sure that forms are submitted from your site and not from an external source. You can use sessions: if value in session, form is okay, otherwise, form was submitted using a bot.

If you're worried about hosting a malicious script, then yes, you'll have to escape all user-entered content for public and admin consumption.

This should make it easier:

function h($string) {
    return htmlspecialchars($string);
}

You may want to consider a template language that will escape your variables for you:

Eg. http://www.h2o-template.org/

Dimitry
  • 6,545
  • 2
  • 20
  • 21
0

Yup, every time.

The only easier way is to use a template that does this for you. Make one yourself, or look into one like XSLT or my personal fave PHPTAL

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • What does the template do for you? I.e, what does the code look like? – Andy Hin Mar 10 '11 at 04:50
  • What it does for you and what it looks like are very different topics. Many templates have different syntax. PHPTAL looks just like xml, for instance. Smarty looks ugly with braces imo, but to each his own. Templating systems enforce structure in your (x)html code, separate business logic from view, keep code clean, and can perform some tasks automatically such as encoding inputs – Explosion Pills Mar 10 '11 at 14:32
0

it also depends on the type of content you are expecting. If for instance you are only expecting letters then you can do

$input = preg_replace("/[^a-zA-Z]*/", "", $input);

or if you are only expecting numbers

$input = preg_replace("/[^0-9]*/", "", $input);

or if it is mixed and other characters would be expected then you will have to use

$input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
Jason
  • 2,687
  • 3
  • 29
  • 40