We all know that parameterized SQL is the way to go when dealing with user input and dynamic SQL, but is casting from string to int (or double, or long, or whatever) as effective if the input you are seeking is numeric?
I guess what I am asking is if this technique alone is infallible in regards to SQL injection?
CAST and CONVERT can be used to convert a string to a number of any data type. For example, you can convert a string to a number of data type INTEGER. TO_DATE converts a formatted date string to a date integer.
PHP provides mysql_real_escape_string() to escape special characters in a string before sending a query to MySQL. This function was adopted by many to escape single quotes in strings and by the same occasion prevent SQL injection attacks.
The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.
I'm no expert, but I'm reasonably sure that this would be safe.
But why take the chance? Use parameterised SQL and you don't ever need to worry about it.
Besides, parameterising your SQL has other advantages, not just injection-protection.
If the string was a valid number before you casted it to integer yes it is safe. But you must make sure that it is a valid integer before casting it to int.
I don't know what server side language you are using but in PHP you can use is_numeric() function. For instance:
$strYouExpectToBeInt = $_POST['id'];
try {
if (false === is_numeric($strYouExpectToBeInt)) {
throw new Exception('id is not a numeric string or a number');
}
$strYouExpectToBeInt = (int)$strYouExpectToBeInt;
if (false === is_int($strYouExpectToBeInt)) {
throw new Exception('id is not a valid integer');
}
// everything is ok, you can use $strYouExpectToBeInt
// in SQL query now
} catch (Exception $e) {
echo $e->getMessage();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With