Possible Duplicate:
What are the best practices for avoiding xss attacks in a PHP site
What are the common defenses against XSS?
I’m trying to make a PHP application I’ve written secure and have a question about escaping output. I switched to using prepared statements with PDO once I learned doing so would prevent SQL injections, and it seems that the other main type of attack is XSS. I build the output for my pages like this (assume the variables have data from the database in them):
$output = '';
$output .= '
<div style="float: left; width: 800px;">
<span>Name:</span><span> ' . $name . '</span>
<span>Address:</span><span>' . $addr . '</span>
<span>Time:</span><span>' . time() . '</span>
</div>';
$output .='[lots more html]';
So, my question is, should I use htmlentities() around every piece of data from the database being output (a typical page has dozens, some possibly hundreds, of variables from the database being output)?
There are two benefits to using
htmlentities():©. In HTML content you should use the appropriate HTML entity instead of inserting a raw special character.For XSS prevention, you could use
htmlspecialchars()instead, but it will only convert some basic characters to HTML entities, namely quotes, ampersand and the less than/greater than characters.In answer to your question, you should use
htmlentities()when outputting any content that could contain user input or special characters.