$string = filter_input (INPUT_POST, 'string', FILTER_SANITIZE_STRING);
$query = sprintf ('SELECT * FROM table WHERE username=\\'%s\\';',
mysql_real_escape_string ($string));
echo $query;
If our input is a string that uses a single quote character, mysql_real_escape_string seems to fail in escaping the character. I’ve tested this with other combinations and it seems that filter_input is the culprit. The string values that it returns appears to be un-escapable. Googling for any similar cases produces no similar results, so I’d just like to think that I’m doing something wrong, or is this an undisclosed bug with filter_input. I’ve checked php’s bug tracker and no similar cases are filed for filter_input.
Let’s say that we do not have access to prepared statements. How can this situation be rectified?
Sorry, this is not an answer - but if $string already contains a sanitized string, why do you need to sprintf() it?
Also your understanding of mysql_real_escape_string seems completely wrong.
// use filter input
$string = filter_input (INPUT_POST, 'string', FILTER_SANITIZE_STRING);
$query = "SELECT * FROM table WHERE username='$string'";,
OR
// use real escape string
$query = "SELECT * FROM table WHERE username=
'" . mysql_real_escape_string ($string) . "'";,
OR
//use sprintf
$query = sprintf ('SELECT * FROM table WHERE username=\\'%s\\', $string )',
echo $query;
Chase the changes through your own code if you want to … by using
string(74) "SELECT * FROM table WHERE username='' or 1 = 1 or '1' = ''"
string(62) "SELECT * FROM table WHERE username='\\' or 1 = 1 or \\'1\\' = \\''"
string(58) "SELECT * FROM table WHERE username='' or 1 = 1 or '1' = ''"
The first one seems to have non escaped single quotes, but filter_input has transformed them into ' so maybe that makes it save to use in a query (I think so, but didn’t test it).
The second one has the single quotes escaped, so it should be safe now, right?
The third one (sprintf), didn’t escape the single quotes, and they are still normal ascii 39 characters. I looks to me like you’d still have to pass the string value through mysql_real_escape_string.
The third one (sprintf), didn’t escape the single quotes, and they are still normal ascii 39 characters. I looks to me like you’d still have to pass the string value through mysql_real_escape_string.
yeah, you are right I think.
I just use prepared statements and escape my output back to html and sleep at night.
I just find it unnerving to see a mix-up of Filtering and Escaping together with a formatting function all bunged together and hoping that you are safe.
FIEO is the rule. If you don’t have some kind of catch at the end of your filter then why bother with it?