Generally speaking, if you wish to add a string to your SQL query, you should escape it immediately before adding it to your SQL query.
I assume that you want to escape all your data at the start of your PHP script, so that you will not have to worry about escaping.
Escaping string for SQL queries shouldn't be included there because that's a bad design method:
- What happens when you add the escaped string to an input element of an HTML form?
The original client's string will be modified.
- It's an inconvenient or problematic way to use prepared statements with the already escaped data.
I think that the following code should be used:
function init_filter_input($method_array /* $_GET, $_POST, or whatever you wish */ )
{
filter_UTF8($method_array); // for a UTF8 encoded string
filter_HTML($method_array);
}
function filter_UTF8($mixed)
{
return is_array($mixed)
? array_map('filter_UTF8',$mixed)
: iconv('UTF-8','UTF-8//IGNORE',$mixed);
}
function filter_HTML($mixed)
{
return is_array($mixed)
? array_map('filter_HTML',$mixed)
: htmlspecialchars(trim($value),ENT_QUOTES);
}
When you want to add a string to your SQL query, you may decide to use prepared statements, or sprintf:
// sprintf example:
query('SELECT ... WHERE username="%s"', $unescaped_username);
function query($query_str, $params)
{
if (is_array($params))
{
$params = array_map('filter_SQL', $params);
$query_str = vsprintf($queryStr, $params);
}
else
$query_str = sprintf($query_str ,filter_SQL($params));
mysql_query($query_str);
}