2

I am building a comment system that will allow users to post code. What security aspects should i be worried of concerning the input? Will it be enough to run the input through the XSS filter and escape special characters before storing it to the database? Something like this function:

function clean($conn,$input){
$input=htmlentities($input);
$input=mysqli_real_escape_string($conn,$input);
return $input;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
admir
  • 193
  • 16
  • 4
    It's just text. Just treat it like any other text with the same precautions. [The Great Escapism (Or: What You Need To Know To Work With Text Within Text)](http://kunststube.net/escapism/) – deceze Apr 21 '15 at 08:11
  • 1
    Excepted some very specific cases, you never need to protect against XSS before querying the database. – Benoit Esnard Apr 21 '15 at 08:12
  • 2
    You should not fight with XSS in your database. Kill it, when you print your data on the page. [htmlspecialchars](http://php.net/manual/en/function.htmlspecialchars.php) – vp_arth Apr 21 '15 at 08:13
  • 1
    Instead of inventing something new, try a library for that purpose. There are several. Like https://github.com/phpsec/phpSec – Michael Apr 21 '15 at 08:13
  • 1
    Since you are using MySQLi, it is preferable to use parameter binding rather than escaping. – halfer Apr 21 '15 at 08:16
  • thank you everyone for your input on the subject :) – admir Apr 21 '15 at 08:36

1 Answers1

4

Code is just text. There's nothing special about code that would require you to do anything differently from regular text (except maybe use the white-space: pre CSS attribute on it):

  1. Prevent SQL injection by SQL-escaping properly once when creating your SQL queries, or preferably use prepared statements. See How can I prevent SQL injection in PHP?
  2. Escape text correctly for output into HTML (when outputting into HTML, not before, not after). See How to prevent XSS with HTML/PHP?

That's it. Done. Also see The Great Escapism (Or: What You Need To Know To Work With Text Within Text) for more background if you need it.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889