Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么要检查mysql\u real\u escape\u string()的返回_Php_Mysql_Security - Fatal编程技术网

Php 为什么要检查mysql\u real\u escape\u string()的返回

Php 为什么要检查mysql\u real\u escape\u string()的返回,php,mysql,security,Php,Mysql,Security,在我读过的每一篇博客/文章/问答中,都没有人建议检查mysql\u real\u escape\u string()返回的值 在我看来,此检查对于确保数据一致性非常重要,因为如果此函数失败,则插入数据库中的值将是一个false positive:一个布尔false类型,转换为string,结果是一个空字符串,而不是您所期望的 根据文件: Returns the escaped string, or FALSE on error. A MySQL connection is required

在我读过的每一篇博客/文章/问答中,都没有人建议检查
mysql\u real\u escape\u string()
返回的值

在我看来,此检查对于确保数据一致性非常重要,因为如果此函数失败,则插入数据库中的值将是一个false positive:一个布尔false类型,转换为string,结果是一个空字符串,而不是您所期望的

根据文件:

Returns the escaped string, or FALSE on error. 

A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used. 
如果您在日志中查看发生了什么,则警告是好的,但不会阻止它的发生

我知道有很少的更改会失败,但是如果至少有一个更改,那么您的应用程序应该会期待它

如果出现以下情况,此功能将失败:

  • 开发人员在调用此函数之前未连接到数据库
  • 调用此函数之前,与数据库的连接失败
  • 服务器(mysql客户端所在的位置)内存不足,无法复制字符串进行转义
这是“正常”用法的一个示例:

我正在使用类似的东西(在mysql的am OO包装中):

这将抛出一个异常,该异常将由异常处理程序捕获,最重要的是,我防止了在数据库中插入假正值,从而确保了数据的一致性


我错过了什么?我是在稳妥行事,还是在妄想?:)

不,我不认为你有妄想症。(或者我们都是偏执狂)


我也确实认为,在mysql查询中避免发送
nothing
绝对是一种好的做法(就像您不想发送
nothing
valued
$\u POST
变量一样)。

我注意到了您提到的问题:

这是“正常”用法的一个示例:

$db=mysql_connect()

好的,在这一点上,你一定要检查连接是否成功。。此外,通过一个好的数据库抽象层,您可以防止用户“忘记”连接到数据库(因为他从不需要手动连接)。(1).

如果您同时失去连接,那么您的查询将失败,因此发送的内容无关紧要(2)


mysql\u real\u escape\u string
是在客户端完成的,因此mysql服务器的内存使用不是问题(3)。

从某种意义上说,由于它是一个函数系列,您缺少了一些东西。而是使用或。这两种方法都提供了参数化查询,可以自动为您转义输入数据。

关心安全性的人都不会建议调用mysql\u real\u escape\u string!别这么做,孩子们。我现在知道了,但是很多人仍然在使用mysql扩展,所以问题是mysql扩展的最佳实践。“我应该提一下。”拉杜马里斯是的,我很感激。我本来打算添加这个作为评论,但是有了所有的链接,我认为作为一个答案会读得更好(而且你没有说明你知道其他扩展…)mysql\u real\u escape\u string()很重要…:)我改了,所以看起来像是“正常”用法。
$db = mysql_connect() or die('Cannot connect to database');
$value = mysql_real_escape_string($_POST['value'], $db);
mysql_query('insert into tablex (value) values ("'.$value.'")', $db) or die('Cannot insert data in database');
class mywrapper{
    // ... [code ...]

    // $this->db is the mysql link identifier
    public function escape($string)
    {
        if(mysql_real_escape_string($string, $this->db) === false)
        {
            throw new Exception('Some message');
        }
    }
} // end class    

    // I'm calling it as 
    // $myWrapper->insert('insert into tablex (value) values ("'.($myWrapper->escape($value)).'")');