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?
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?
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:
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
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');