Prevent XSS attacks

2019-01-18 16:59发布

问题:

Is this code secure to prevent XSS attacks ??

<?php
   $string = "<b>hello world!</b>";
   echo "without filtering:".$string;
   echo "<br>";
   $filtered = htmlspecialchars($string); // insert into database filtered
   echo "After filtering:".$filtered;
   echo "<br>";
   $de_filtering = htmlspecialchars_decode($filtered); //retrieve from database and display
   echo "After de-filtering:".$de_filtering;        
  ?>

回答1:

You should not encode HTML-Specialchars when inserting into database, that way data is manipulated (and maybe different when editing the dataset). You should rather encode them when displaying it.

But yes, htmlspecialchars() is enough to prevent XSS as long as you don't forget to use it. The way YOU use it however is as secure as before. XSS is prevented through the encoded version, the database does not care about it.



回答2:

No, XSS is independent of the database. To avoid SQL-injection, you want to escape using something like mysql_real_escape_string or use prepared statements, but to avoid XSS you need to escape when outputting to HTML.

And there are a couple of gotchas there as well. Take a look at the OWASP XSS prevention cheat sheet. It explains how to escape for different context.

htmlspecialchars/htmlentities will protect you if you are outputting untrusted data between tags, but will not protect you if you are outputting it in say a javascript event handler like this:

&lt;button onclick="confirm('do you want to delete &lt;?php echo htmlspecialhars($untrusted_data) ?&gt;')"&gt;

This is because you are escaping for HTML and not javascript.



回答3:

Nope - you're filtering the data before putting it into the database (which is unnecessary), but cancelling out the filter when outputting the data.

Store the data in the database unfiltered, and escape it when outputting:

 echo htmlspecialchars($unfiltered_data_from_database);


标签: php xss