针对SQL注入的ctype_alnum

Sam*_*uel 4 php sql security sql-injection

准备好的语句不允许参数化表名.为了确保不能插入任何代码,我想使用ctype_alnum来验证进入数据库模块的所有表名(删除下划线之后),以保护应用程序免受其他部分中的错误的影响.

function insert($table) {
    if(!ctype_alnum(str_replace("_", "", $table)))
        throw new Exception("Invalid table name");
    $sql = "INSERT INTO $table VALUES value=:value";
    #... prepare and execute
}
Run Code Online (Sandbox Code Playgroud)

有没有足够的攻击?我正在考虑例如多字节角色攻击

Mar*_*łek 8

我不知道在这种情况下会有什么攻击,但我不会像你那样做,因为$table它也可能包含可能不存在的表.

你应该$tables接受白名单,所以我会这样做:

function insert($table)
{
    $table = trim($table);

    if (!ctype_alnum(str_replace("_", "", $table))
        || !in_array($table, $this->tables)
    ) {
        throw new Exception("Invalid table name");
    }


    $sql = "INSERT INTO $table VALUES value=:value";

    echo $sql;
    #... prepare and execute
}
Run Code Online (Sandbox Code Playgroud)

它将确保您的代码是安全的,如果有人拼写错误的表名,您甚至不会尝试执行代码.实际上,在这种情况下,您可以在ctype_alnum检查白名单数组中是否存在值时从条件中删除.

  • 有效表名的白名单数组是个不错的主意!**+ 1** (3认同)