在PHP中过滤掉MySQL查询 [英] Filtering out MySQL query in PHP

查看:182
本文介绍了在PHP中过滤掉MySQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在对涉及一些用户输入的MySQL数据库进行一些查询.我想知道如何防止注入攻击,例如,如果有人键入

Hey there, I'm doing some queries to a MySQL database that involves some user-input.. And I was wondering how to prevent injection attacks, like, for example, if someone were to type

"; a-MySQL query here;"

它将被执行,这将使人们可以访问损害我的系统.我想知道如何防止这种情况发生,可能会创建一个函数,以过滤掉查找不良语句的查询?或不允许;特点?

It would be executed, this would allow people access to compromise my system. I'm wondering how i could protect against things like this, possibly create a function that filters out the query looking for bad statements? or perhaps not allowing the ; character?

  • 如今预防注射攻击的常用方法是什么?
  • 我应该怎么做?
  • 此解决方案对那些知道通过更改我的数据库正在做的事情的人有多有效.

推荐答案

唯一的方法是正确地转义用户提交的数据.其他人指出了这样做的一些方法.

The only way is to properly escape user-submitted data. Others have pointed out some ways of doing so.

还有另一种方法:准备好的声明和占位符.每个 modern PHP数据库接口都支持预备语句,包括 mysqli PDO .

There's another way: prepared statements and placeholders. Prepared statements are supported by every modern PHP database interface, including mysqli and PDO.

让我们以PDO为例.假设我们要更新用户提交的表foo中的一些数据.

Let's use PDO as a demonstration. Let's say we wanted to update a bit of data in the table foo submitted by a user.

$sql = 'UPDATE foo SET bar = ? WHERE user_id = ?';
$sh = $db->prepare($sql);
$sh->execute(array( $_POST['bar'], $_SESSION['user_id'] ));

传递给execute的数组中的变量替换查询中的问号占位符.发生这种情况时,它们会自动转义并引用.您无需手动对其进行转义即可使它们安全地放入数据库中!

The variables in the array passed to execute replace the question mark placeholders in the query. When this happens, they are automatically escaped and quoted. You don't need to manually escape them to make them safe to put in the database!

另一方面,您仍然需要对它们进行过滤以过滤意外内容,例如HTML,Javascript,期望数字的字母等.确保数据安全插入数据库是

On the other hand, you will still need to filter them for unexpected content, like HTML, Javascript, letters where you expect numbers, etc. Making data safe to insert into the database is only half of the battle.

这篇关于在PHP中过滤掉MySQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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