SQL Injection Protection - Cast from string to int

二次信任 提交于 2019-12-05 03:34:55

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();
}

Its safe with regards to sql injection prevention but not really a good idea as you get an exception, which you always want to avoid if possible as exceptions are expensive. You should really properly sanitize the input. And of course the user can still alter the value to any range within an int32 value.

Probably, but worth testing.

Regarding Richard's answer, I've sometimes had trouble with IsNumeric() being a little more liberal in what it will accept as a valid number than the actual CAST to numeric (depends on localization settings, actually). Stuff like "-0", "3E-5", "5.000.000" sometimes satisfies IsNumeric, but doesn't cast properly. So I usually do a full try, catch around the actual cast statement instead.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!