我需要在laravel中清除DB :: query调用的用户输入吗? [英] Do I need to clean user input for DB::query calls in laravel?

查看:209
本文介绍了我需要在laravel中清除DB :: query调用的用户输入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读Laravel 文档我看到:

Reading the Laravel documentation I see that:

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

如果我仅以以下方式编写查询,这仍然适用吗?

Does that still apply if I only craft queries in the following manner?

DB::query("SELECT * from table WHERE id like " . $id);

推荐答案

让我们采用该句子并强调关键短语:

Let's take that sentence and emphasise the key phrase:

无需清理作为绑定传递的字符串.

在您的示例中,$id没有作为绑定传递,它只是被注入到原始SQL中,因此它不受保护.

In your example, $id is not being passed as a binding, it is just being injected into the raw SQL, so it is not protected.

您应遵循防止SQL注入的标准做法:

You should follow standard practice for preventing SQL injection:

  • 在这种情况下,如果输入始终是整数,则可以使用intval($id)
  • 您可以使用DB::getPdo()/DB::getReadPdo()获取基础的 PDO 对象,并使用PDO::quote()正确地转义字符串
  • 尽管文档很差,但是Laravel的DB门面可以运行完全参数化的查询,例如DB::select('SELECT * FROM users WHERE users.id = ?', array($userId));
  • in cases like this, where the input is always an integer, you could use intval($id)
  • you could get the underlying PDO object with DB::getPdo()/DB::getReadPdo() and use PDO::quote() to correctly escape strings
  • although the documentation is rather poor, Laravel's DB facade can run fully parameterised queries, such as DB::select('SELECT * FROM users WHERE users.id = ?', array($userId));

参数化查询通常被认为是预防注入的黄金标准,也是Eloquent在使用查询生成器时在内部使用的标准.这个想法是,您首先要为数据库(或至少是数据库驱动程序)提供完整的查询,而根本没有用户输入,因此,毫无疑问应该使用哪些表和列.然后,您将用户输入作为完全独立的数据传递,该数据实际上从未写入SQL中,而是仅应用于已发送的查询.

Parameterised queries are usually considered the gold standard in injection prevention, and are what Eloquent is using internally when you use the query builder. The idea is that you first give the database (or, at minimum, the database driver) the complete query with no user input at all, so there is no doubt which tables and columns should be in use. You then pass in the user input as completely separate data, which is never actually written into the SQL, just applied to the query you already sent.

尽管如此,参数化查询无法为您做任何事情-例如,大多数库

Parameterised queries can't do everything for you, though - for instance, most libraries, including PDO, can't bind a table or column name as a parameter. That's because it will actually create a different query every time it is run, negating the separation between query and data. If you want to do that, you therefore need some other method of ensuring safety - usually, a whitelist of allowed values is the best idea.

这篇关于我需要在laravel中清除DB :: query调用的用户输入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆