如何从 Laravel 中的 SQL 注入中保护此 sql 查询?

How can I secure this sql query from SQL Injection in Laravel?

我正在尝试在 Laravel 中创建 rest API。如何从 sql 注入中保护这样的 SQL 查询?

Route::get('api/restaurant/id/{id}', 'RestaurantController@getRestaurantById');

public function getRestaurantById($id) {
        $restaurant = Restaurant::where('id', $id)->first();

        return $restaurant;
    }

Laravel 的数据库查询构建器为创建和 运行 数据库查询提供了一个方便、流畅的界面。它可用于在您的应用程序中执行大多数数据库操作,并适用于所有支持的数据库系统。

Laravel 查询生成器使用 PDO 参数绑定来保护您的应用程序免受 SQL 注入攻击。无需清理作为绑定传递的字符串。 introduction

请注意,如果您构建原始 SQL 语句并执行这些语句或使用原始表达式,您将不会自动受到保护。

Eloquent uses parameter binding behind the scene, which safely escapes any input used in where(). The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

根据 Laravel 文档

The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

还有

Raw statements will be injected into the query as strings, so you should be extremely careful to not create SQL injection vulnerabilities.

在构建原始 SQL 语句或表达式时,您应该始终使用参数化查询。

Laravel -> Database: Query Builder -> Introduction

Laravel -> Database: Query Builder -> Raw Expression

如果您使用 eloquent 从数据库中保存和检索数据,则无需担心 sql 注入

如果您使用 laravel ORM 构建您的 sql 查询,您的查询将自动受到保护,免受 sql 注入。

例如:

$restaurant = Restaurant::where('id', $id)->first();

这个查询是由 laravel ORM 创建的,如果你 运行 dd(Restaurant::where('id', $id)->toSql()) 你会看到 id 没有直接注入查询:

SELECT * FROM restaurants WHERE id = ?

您可以使用 DB::select()DB::raw() ... e.t.c 运行 sql 原始查询。 如果您查看 laravel 文档,您会发现每个原始方法都有数组参数,通常是第二个参数。 例如:

DB::select('SELECT * FROM restaurants WHERE id = ?', [$id]);
Restaurant::whereRaw('id = ?', [$id])->first();
...
DB::raw('SELECT * FROM restaurants WHERE id = ?', [$id]);

以上每个查询都是安全的 sql 注入。

Do not write queries like this DB::select("SELECT * FROM restaurants WHERE id = $id"); This can be extremly dangerous for your app.

有关更多信息,请查看此处:https://laravel.com/docs/5.8/database#running-queries

希望对您有所帮助。