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

前端 未结 2 1502
失恋的感觉
失恋的感觉 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: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();
    

提交回复
热议问题