mysql_real_escape_string和addslashes有什么区别?
" mysql_real_escape_string"和" addslashes"都用于在数据库查询之前对数据进行转义,所以有什么区别? (此问题与参数化查询/ PDO / mysqli无关)
解决方案
看来mysql_real_escape_string是二进制安全的,文档指出:
If binary data is to be inserted, this function must be used.
我认为总是使用" mysql_real_escape_string"比添加斜杠更安全。
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] ) mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.
string addslashes ( string $str ) Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
它们影响不同的角色。 mysql_real_escape_string特定于MySQL。 Addslashes只是一个通用函数,可能适用于其他事物以及MySQL。
当我们接收二进制数据时,应使用" mysql_real_escape_string"," addslashes"用于文本输入。
我们可以在此处看到差异:mysql-real-escape-string和Addslashes
mysql_real_escape_string()具有通过可选的link_identifier参数相对于数据库字符集正确转义文本输入的添加好处。
字符集意识是至关重要的区别。 addslashes()
将在每个要转义的字符的每八位二进制表示形式之前添加一个斜杠。
如果我们使用某种形式的多字节字符集,则可能,尽管可能仅是由于字符集的不良设计,但十六位或者三十二位字符表示形式的一半或者一半与字符的八位相同addlashes()
将添加一个斜线。
在这种情况下,我们可能会在不应该转义的字符之前添加斜杠,或者更糟的是,我们可能会在16(或者32)位字符的中间出现斜杠,这会破坏数据。
如果需要在数据库查询中转义内容,则应尽可能使用" mysql_real_escape_string()"。如果我们确定数据库或者表仅使用7或者8位ASCII编码,则可以使用addslashes()
。