Should I use htmlentities () for all output? (prevention of XSS attacks)

Possible duplicate:
What are the best methods to prevent xss attacks on a PHP site
What is the general protection against XSS?

I am trying to make a PHP application that I wrote safe, and you have a question about escaping output. I switched to using prepared statements with PDO as soon as I found out that this would prevent SQL injections, and it seems that the other main type of attack is XSS. I build the output for my pages as follows (suppose 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 htmlentities() be used for each piece of data from the output database (a typical page contains dozens, and sometimes hundreds, of variables from the output database)?

+4
source share
2 answers

There are two advantages to using htmlentities() :

  • XSS Prevention
  • Convert special characters to corresponding HTML objects, for example, it converts a copyright symbol to &copy; . In HTML content, you should use the appropriate HTML object instead of pasting an unprocessed special character.

To prevent XSS, you can use htmlspecialchars() instead, but it will only convert some basic characters to HTML objects, namely quotation marks, ampersands, and less / more characters.

In response to your question, you should use htmlentities() to output any content that may contain user input or special characters.

+3
source

htmlspecialchars() more than enough. htmlentities is for different purposes, not for XSS.

+1
source

Source: https://habr.com/ru/post/1445527/


All Articles