tags:

views:

49

answers:

3

Hi ,

As it says in the title , how can I tell if the mysql_real_escape_string is working how it should without waiting to be hacked ?

+1  A: 

Check the values you get back from it.

Send it some text that it should escape, such as Ed O'Neil (Which should come back as Ed O''Neil or Ed O\'Neil)

R. Bemrose
Would this be ok then ? $post = $_GET['post']; if(is_numeric($post)) { $post = mysql_real_escape_string($post); } else { die("NAUGHTY NAUGHTY"); } mysql_select_db("*******", $******); $content = mysql_query("SELECT * FROM tbl_***** WHERE Id='" . $post . "'");
Oliver Bayes-Shelton
It seems to me that if is_numeric($post) is true, $post wouldn't need to be escaped as it's already a number. Still, it can't hurt to double-check.
R. Bemrose
If i expect a numeric value i usually just use "SELECT foo FROM bar WHERE baz=" . (int)$foo; If the value is not a number it returns 0, resulting in (usually, depending on query) an empty result set and any other number will be stripped of all non-numerical characters (see behaviour of integer casts in the manual). For inserts/updates there has to be validation though as 0 might not always be ok. Advantage is: Much shorter than escaping and makes it clear for others reading the code that it's a number. About speed: Not sure there but i think it might be faster than escaping.
dbemerlin
+1  A: 

Create a unit test that sends it all characters it should escape and checks it output.

BUT: Why don't you simply use parameterized queries with PDO? Like:

$dbh = new PDO([...]);
$sth = $dbh->prepare("SELECT foo FROM bar WHERE baz=:baz");
$sth->execute(array(":baz" => $mybaz));

It is the safest way and thanks to PDO it's nearly as easy as in Perl.

dbemerlin
+1  A: 
avirtuos