I've read quite a few q&a's on filtering user input here, but most of the time the answer is that it depends on what you're doing. Here's what I'm doing:
Data submitted via a form that will be used in a MySQL query:
function clean($field, $link)
{
return mysql_real_escape_string($field, $link);
}
Data submitted via a form that will be displayed back on the HTML/PHP page or in an email:
function output_html($value)
{
return stripslashes(htmlspecialchars($value));
}
Data displayed from database:
function output_db($value)
{
return stripslashes($value);
}
Is this sufficient for my needs? Is there something I'm not considering?
Thanks!
Use mysql_real_escape_string()
when inserting strings into SQL queries, no matter where the input comes from.
Use htmlspecialchars()
or htmlentities()
when inserting strings into HTML code, no matter where the input comes from.
Use urlencode()
when inserting values into the query string of a URL, no matter where the values come from.
If this data comes from the user, then you should definitely do these things because there is the chance that the user is trying to do bad things. But security aside--what if you want to insert a legitimate string into a SQL query and the string just happens to have a single quote character in it? You still must escape it.
I would really look into using something like PDO if you are starting out. You will eventually want to migrate that way, so why not start now.
PDO will cleanse your input automatically, which is great. It will also use prepare() statements, so you are guaranteed a single query, which prevents someone attacking with a "; DROP TABLE xxx;" or such.
http://php.net/manual/en/book.pdo.php
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