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

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


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!


There are a lot of ways to do XSS (See http://ha.ckers.org/xss.html) and it's very hard to catch.

I personally delegate this to the current framework I'm using (Code Igniter for example). While not perfect, it might catch more than my hand made routines ever do.