tanios
tanios

Reputation: 53

PHP MySQL injection security: Does verifying that $_GET input is numeric provide enough protection?

I realized that the following part of my application has potential for MySQL injection.

$id= $_GET['id'];
$query = "SELECT * FROM clients WHERE id = $id";
//run query

Is it enough security for me to check is_numeric($id) before running the MySQL query? Or is it necessary for me to re-write my code using prepared statements?

Upvotes: 1

Views: 299

Answers (3)

halfer
halfer

Reputation: 20469

If you don't have time to rewrite your queries using prepared statements, I would say I'd have more confidence in casting the user input.

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

Since this variable is now an int, there is no way it can contain malicious input. Of course, you should still do any necessary range validation on it (e.g. if negative numbers should be disallowed).

I've assumed this column is an integer, but (float) can be used in the same way here, for data that is numeric but not integer.

For the avoidance of doubt, parameter binding is still the best approach to injecting user input into your queries. My answer here is intended to answer the thrust of the question directly i.e. is there a way to make queries safe without binding? The answer above shows that the answer is yes.

Upvotes: 0

Max Worg
Max Worg

Reputation: 2972

It will reduce the attack surface if you restrict the parameters to just an integer but you also want to validate the parameter on the server side (don't leave the security checks on the client-side since they client can bypass those very easily).

For application security (and especially PHP security since it is riddled with security headaches) it is always a good idea to consider that all user-supplied data is malicious. So double check that all parameters fit into the criteria expected before allowing the application to act on that data and process it.

You will do yourself a favor by using PHP prepared SQL statements as those are an added mechanism (on top of your own validation) to significantly reduce the injection attack surface.

Here is a resources to get you more familiar with PHP prepared statements:

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

The idea is that it avoids injection attacks by specifying what kind of datatype the parameter is and builds a safer query string for you. But again - always inspect incoming/user-supplied data before processing it further.

Upvotes: 0

thatidiotguy
thatidiotguy

Reputation: 9011

You SHOULD use prepared statements as mysql_* functions are deprecated. That being said, a numeric value would make that SQL statement definitively safe as SQL injections require the variable to actually have SQL like statements in them.

An example would be 1;-

Upvotes: 1

Related Questions