views:

44

answers:

4

Since there is no function to check whether a string is escaped before entering it to the db, how can I do this with regex?

$string = 'some" string';
if(!preg_match('//',$string))
{
   $string = mysqli_real_escape_string($string);
}

php manual:

mysqli_real_escape_string backslashes characters encoded NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

+1  A: 

There is no function to check whether a string is escaped, because there is no logical way to tell if a string is escaped.

It\'s nice

Is that escaped? How do you know? Is it an escaped apostrophe, or an unescaped backslash and apostrophe?

Escaping is a process, not a property of a string. You must always know whether you've escaped a string for a particular context. The best way to do that is to keep your strings raw and unescaped until the time they leave for another context. So don't call mysql_real_escape_string until you're actually concatenating into an SQL string. Don't call htmlspecialchars until the moment you're echoing into HTML output.

bobince
+3  A: 

Don't try to do this.

If you try to come up with a way to know for sure whether a string is escaped or not, someone can just come in and make a string that will fool your detection method.

For example, if you used "\" as a test to make sure slashes are escaped, I can just give you a string like "'; DROP DATABASE dbname(); --\\", which passes your inspection but is still horribly wrong.

If you can't use stored procedures and/or proper parameter handling for whatever reason, the only way to make sure your strings are clean is to clean every string for every untrusted source.

Welbog
+1  A: 

You don't. Use prepared statements and bound variables. Refer to mysqli_prepare and mysqli_stmt_bind_param.

Arkh