What are the best practices for avoiding xss attacks in a PHP site [closed]

I have PHP configured so that magic quotes are on and register globals are off.

I do my best to always call htmlentities() for anything I am outputing that is derived from user input.

I also occasionally seach my database for common things used in xss attached such as...

<script

What else should I be doing and how can I make sure that the things I am trying to do are always done.


Escaping input is not the best you can do for successful XSS prevention. Also output must be escaped. If you use Smarty template engine, you may use |escape:'htmlall' modifier to convert all sensitive characters to HTML entities (I use own |e modifier which is alias to the above).

My approach to input/output security is:

  • store user input not modified (no HTML escaping on input, only DB-aware escaping done via PDO prepared statements)
  • escape on output, depending on what output format you use (e.g. HTML and JSON need different escaping rules)

I'm of the opinion that one shouldn't escape anything during input, only on output. Since (most of the time) you can not assume that you know where that data is going. Example, if you have form that takes data that later on appears in an email that you send out, you need different escaping (otherwise a malicious user could rewrite your email-headers).

In other words, you can only escape at the very last moment the data is "leaving" your application:

  • List item
  • Write to XML file, escape for XML
  • Write to DB, escape (for that particular DBMS)
  • Write email, escape for emails
  • etc

To go short:

  1. You don't know where your data is going
  2. Data might actually end up in more than one place, needing different escaping mechanism's BUT NOT BOTH
  3. Data escaped for the wrong target is really not nice. (E.g. get an email with the subject "Go to Tommy\'s bar".)

Esp #3 will occur if you escape data at the input layer (or you need to de-escape it again, etc).

PS: I'll second the advice for not using magic_quotes, those are pure evil!