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()orhtmlentities()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.