如何防止XSS和CSS注入? [关闭]

I've made a function to deal with CSS and XSS injecting but its still getting through.

Someone said the following to me, but I'm not sure what it means:

On your sanitize_input function, do a strip_tags to strip all html tags that may have been added through the form. Read php.net on strip_tags.

Here's my code:

private function sanitizeInput() {
    foreach($_POST as &$post) {
        $post = $this -> db -> real_escape_string($post);
    }
}

The code you have makes your input safe to insert into a database. However, what is safe for a database may not be safe for HTML.

Typically, you shoud use that function to insert the data, and when you retrieve it later you run it through something like htmlspecialchars before outputting it. However, do NOT do this before saving the data, only do it at the final output stage.

You're doing the work in the wrong places.

To prevent SQL injection, use prepared/parameterized queries with PDO. This fundamentally separates the data from the command, making it immune to general SQL injection problems.

Your problem with XSS is no doubt because you are using arbitrary data in an HTML context without any escaping. On output of your data, use htmlspecialchars(). This will encode all special characters into their proper entities.

This depends... do you want to be able to save tags, but not have them rendered in the browser? If so, use htmlentities. If not, use strip_tags.

Perhaps:

private function sanitizeInput() {
  foreach($_POST as $key => $val) {
    $_POST[$key] = $this->db->real_escape_string(htmlentities($val, ENT_QUOTES));
  }
}

It really depends on what you're trying to accomplish.

The example above would convert: A 'quote' is <b>bold</b> to A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;

This solution, however, isn't ideal. You shouldn't convert data before saving into a database. Instead, you'd want to deal with the data after querying it FROM the database.