Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the real way to sanitize user input and output safely and conveniently

Tags:

php

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?

like image 315
dotslashlu Avatar asked Dec 12 '22 09:12

dotslashlu


2 Answers

Simple: Don't filter input. Escape output.

  • When you put something in a MySQL query with the mysql extension, use mysql_real_escape_string. (Even better, switch to PDO and use prepared statements.)
  • When you print something in a HTML page, use htmlspecialchars.
  • When you put something in a shell command, use escapeshellcmd/escapeshellarg.
  • For urls, use urlencode

See this answer too: PHP escaping input variables

like image 126
Arnaud Le Blanc Avatar answered Feb 02 '23 00:02

Arnaud Le Blanc


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.

like image 44
jah Avatar answered Feb 02 '23 01:02

jah