Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to filter/sanitize data: before database insertion or before display?

Tags:

As I prepare to tackle the issue of input data filtering and sanitization, I'm curious whether there's a best (or most used) practice? Is it better to filter/sanitize the data (of HTML, JavaScript, etc.) before inserting the data into the database, or should it be done when the data is being prepared for display in HTML?

A few notes:

  • I'm doing this in PHP, but I suspect the answer to this is language agnostic. But if you have any recommendations specific to PHP, please share!
  • This is not an issue of escaping the data for database insertion. I already have PDO handling that quite well.

Thanks!

like image 232
Justin Stayton Avatar asked Aug 13 '09 21:08

Justin Stayton


2 Answers

When it comes to displaying user submitted data, the generally accepted mantra is to "Filter input, escape output."

I would recommend against escaping things like html entities, etc, before going into the database, because you never know when HTML will not be your display medium. Also, different types of situations require different types of output escaping. For example, embedding a string in Javascript requires different escaping than in HTML. Doing this before may lull yourself into a false sense of security.

So, the basic rule of thumb is, sanitize before use and specifically for that use; not pre-emptively.

(Please note, I am not talking about escaping output for SQL, just for display. Please still do escape data bound for an SQL string).

like image 54
jason Avatar answered Oct 12 '22 02:10

jason


i like to have/store the data in original form. i only escape/filter the data depending on the location where i'm using it.

  • on a webpage - encode all html
  • on sql - kill quotes
  • on url - urlencoding
  • on printers - encode escape commands
  • on what ever - encode it for that job
like image 30
coding Bott Avatar answered Oct 12 '22 00:10

coding Bott