Prevent SQL injection for queries that combine the query builder with DB::raw()

前端 未结 2 1500
失恋的感觉
失恋的感觉 2021-01-12 03:38

In Laravel 4, I want to protect some complex database queries from SQL injection. These queries use a combination of the query builder and DB::raw(). Here is a simplified ex

相关标签:
2条回答
  • 2021-01-12 04:19

    I discovered the query builder has a method called setBindings() that can be useful in this instance:

    $field = 'email';
    $id = 1;
    $user = DB::table('users')->select(DB::raw(":field as foo"))
            ->addSelect('email')
            ->whereId(DB::raw(":id"))
            ->setBindings(['field' => $field, 'id' => $id])
            ->get();
    
    0 讨论(0)
  • 2021-01-12 04:21

    Eloquent uses PDO under the hood to sanitize items. It won't sanitize items added to SELECT statements.

    The mysqli_real_escape_string method is still useful for sanitizing SQL strings, however.

    Consider also (or instead) keeping an array of valid field names from the users table and checking against that to ensure there isn't an invalid value being used.

    $allowedFields = ['username', 'created_at'];
    
    if( ! in_array($field, $allowedFields) )
    {
        throw new \Exception('Given field not allowed or invalid');
    }
    
    $user = DB::table('users')
                ->select(DB::raw("$field as foo"))
                ->whereId(1)->get();
    
    0 讨论(0)
提交回复
热议问题