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?
Simple: Don't filter input. Escape output.
mysql_real_escape_string
. (Even better, switch to PDO and use prepared statements.)htmlspecialchars
.escapeshellcmd
/escapeshellarg
.urlencode
See this answer too: PHP escaping input variables
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With