4

Security should always be the first thing to consider, right? I think this question is so important that someone should have asked before, but I didn't find a satisfying answer for me in search results.

I need both to store user's article contents in database and output it safely. But there's so many ways to do this. I can do this using filter_var() ,strip_tags(), mysql_real_escape_string(),stripslashes()...etc. I can't chose one to use, and i can't confirm whether it's safe enough to use one of them.

What is the best practice for sanitizing input and output?

Bojangles
  • 99,427
  • 50
  • 170
  • 208
dotslashlu
  • 3,361
  • 4
  • 29
  • 56
  • 4
    If you think about it, there's always just one right way to escape data. It's been asked (and answered) many times before, though. Here's [one of my own answers](http://stackoverflow.com/questions/6475225/how-to-cleanse-a-string-to-avoid-sql-injection-and-the-most-common-types-of-attac/6475262#6475262) on the topic. – Kerrek SB Sep 19 '11 at 17:27
  • So many duplicates in the "related" section – Pekka Sep 19 '11 at 17:27

2 Answers2

11

Simple: Don't filter input. Escape output.

See this answer too: PHP escaping input variables

Community
  • 1
  • 1
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
2

In very simple terms "escape/encode for the output context". That's all there is to it.

When you want to store something in mysql you're producing a mysql statment. Context: mysql statement. Encode/escape for mysql statments by using prepared statements which do it for you, or by quoting data using a PDO adapter instance, or by using mysql_real_escape_string (as a last resort).

When you want to output something in an HTML page, Context: html data. Encode for HTML with htmlspecialchars, but be aware that htmlspecialchars is not really sufficient for html attributes because spaces also need to be encoded in this context, as do quotes of both kinds.

Remember that css and javascript are their own context - don't treat them like HTML.

jah
  • 2,056
  • 1
  • 18
  • 35