传递数值变量并防止SQL注入

qv7cva1a  于 2022-10-22  发布在  PHP
关注(0)|答案(4)|浏览(126)

我有这样一个查询:

SELECT name FROM mytable WHERE id = $id

其中$id由用户给出。我确实为输入变量添加了斜线。只使用(int)$id来阻止SQL注入就足够了吗?或者,在将$id传递给查询之前,我必须检查is_numeric(int)$id吗?
已编辑:脚本语言为PHP。

e5njpo68

e5njpo681#

是的,使用(int)intval()强制转换变量将确保其结果仅为数字,没有其他字符。这是一种很好的方法来防御SQL注入攻击,但它当然只适用于数值变量。
有关SQL注入防御方法的更多详细信息,请参阅我的演示文稿SQL Injection Myths and Fallacies或我的书SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming中的章节。

p4tfgftt

p4tfgftt2#

我将放弃思考如何安全地将数字附加到查询字符串的想法,而只需继续使用准备好的语句。它们写起来稍微冗长乏味,但更安全——如果你养成了这个习惯,你就不用担心你在这种或那种情况下做得是否正确,也许有时是数字,有时是字符串,你使用了正确的转义机制吗?

hgb9j2n6

hgb9j2n63#

询问$id是否是一个整数,是否等于或大于0。否则,用户输入注入尝试很可能正在进行。
例子:
$id=(false!==(int)$_GET['id']>=0)?(int)$_GET['id']:die(header(“Location:./index.php”);

rseugnpd

rseugnpd4#

function mysql_prep( $value ) {
    $magic_quotes_active = get_magic_quotes_gpc();
    $new_enough_php = function_exists( "mysql_real_escape_string" ); // i.e. PHP >= v4.3.0
    if( $new_enough_php ) { // PHP v4.3.0 or higher
        // undo any magic quote effects so mysql_real_escape_string can do the work
        if( $magic_quotes_active ) { $value = stripslashes( $value ); }
        $value = mysql_real_escape_string( $value );
    } else { // before PHP v4.3.0
        // if magic quotes aren't already on then add slashes manually
        if( !$magic_quotes_active ) { $value = addslashes( $value ); }
        // if magic quotes are active, then the slashes already exist
    }
    return $value;
}   

$username = trim(mysql_prep($_POST['username']));

使用该功能确保该死的安全!!!:D

相关问题