2

I am using PDO to users input, but right now I'm not using PDO when displaying content from my MySQL database (still the old fashioned way with SQL commands..).

Is it necessary to filter/sanitiza inputs from users when inserting data to a MySQL database?

AND, if the way to go is to sanitize the output instead, then what is the best way to sanitize output? Am I good to go, if I just use htmlspecialchars() or do i need to use strip_tags() and other things also?

I am using placeholders and prepared statements.

Thank you.

2by
  • 1,083
  • 5
  • 22
  • 39

2 Answers2

6

You're confusing different sanitizing here :

  • The SQL sanatizing for data to insert to your DB. With prepared query with params, no need to escape, PDO do it internally. If you don't use prepared queries, use them. It's bullet-proof (as far as I know).

  • The data you get from your DB and output as HTML : here you have to sanatize before printing it to your user (to prevent XSS), either by using htmlspecialchars() , htmlentites() or strip_tags(), depending what you want to escape or delete.

Claaker
  • 257
  • 2
  • 9
  • If i want to escape the string so its 100% safe – 2by Apr 12 '12 at 18:31
  • 1
    You'll be safe with each of these functions, but use the one you need : `strip_tags` strips the HTML code, opposed to `htmlspecialchars` wich only espace them (so they still will be dispayed, but not interpreted by the browser). `htmlentities` will also encode characters like àéè. If your application is UTF-8 powered, just use `htmlspecialchars`. See http://stackoverflow.com/questions/7232793/should-i-use-both-striptags-and-htmlspecialchars-to-prevent-xss – Claaker Apr 12 '12 at 18:37
  • Use htmlentities() instead of htmlspecialchars(). – Marcus Adams Apr 12 '12 at 18:43
  • @Marcus : any good reason to use it instead of basic `htmlspecialchars()`, in the case you're already using an encoding that handle non-ASCII characters ? – Claaker Apr 12 '12 at 18:46
  • Well just go for `htmlspecialchars()`. Using `htmlentites` would uselessly convert (and expend, making the output heavier) non-ASCII characters already well-handled by your internal encoding. – Claaker Apr 12 '12 at 19:19
  • I found that it might be a good idea to sanitize in some way, to i use the PHP filter `filter_var($var, FILTER_SANITIZE_STRING, ENCODE_QUOTES);` – 2by Apr 15 '12 at 22:26
5

If you're properly using parameterized queries, then no, you don't have to escape. That'd actually insert escaped data into the database, so you'd get the escapes coming back our later when you select the data.

However, just switching to PDO does NOT make your code any safer, e.g. if you do

$sth = $db->prepare("INSERT INTO sometable (x) VALUES ($_GET[x])");

is still utterly vulnerable to injections attacks, since you're not using placeholders.

Marc B
  • 356,200
  • 43
  • 426
  • 500