Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent XSS attacks

Tags:

php

xss

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;        
  ?>
like image 452
wfareed Avatar asked Nov 22 '25 15:11

wfareed


2 Answers

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.

like image 165
TimWolla Avatar answered Nov 25 '25 04:11

TimWolla


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.

like image 33
Erlend Avatar answered Nov 25 '25 04:11

Erlend