Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does is_numeric() mean a var is safe for MySQL?

Question says it all hopefully, if I check a variable returns true for is_numeric(), is it ok to put directly into the MySQL query, or do I need to apply standard escaping? I'm thinking null character, overflow exploits and stuff.

An ambiguous example would be:

if(is_numeric($_GET['user_id'])) {
    mysql_query("SELECT * FROM `users` WHERE id = ".$_GET['user_id']);
}

The datatype in MySQL is INT().

like image 599
Dunhamzzz Avatar asked Dec 09 '10 09:12

Dunhamzzz


3 Answers

The safest way in my opinion is to convert the user_id to an integer, if it's invalid it will return 0.

$user_id = (int) $_GET['user_id'];

if ($user_id > 0) {
    mysql_query("SELECT * FROM `users` WHERE `id` = " . $user_id);
}
like image 144
fire Avatar answered Sep 20 '22 18:09

fire


Considering that "10e3" is_numeric, no.

If you want numbers (as in, only digits), you'll have to check for ctype_digit (which would still break SQL for numbers like 0123) or cast the number to an int or float. If it's acceptable for the number to be something other than all digits, you'll need to apply the SQL safe escaping and quoting.

like image 36
deceze Avatar answered Sep 20 '22 18:09

deceze


From http://php.net/manual/en/function.is-numeric.php:

Be careful when using is_numeric() to escape SQL strings. is_numeric('0123') returns true but 0123 without quotes cannot be inserted into SQL. PHP interprets 0123 without quotes as a literal octal number; but SQL just throws a syntax error.

like image 45
Matt Asbury Avatar answered Sep 20 '22 18:09

Matt Asbury