PHP addslashes and mysql_real_escape_string

  • 2020-03-31 20:15:49
  • OfStack

It is a good explanation of the difference between addslashes and mysql_real_escape_string. Although many PHP programmers in China still rely on addslashes to prevent SQL injection (including me), I still recommend you to strengthen the check of preventing SQL injection in Chinese. The problem with addslashes is that a hacker can use 0xbf27 instead of a single quote, while addslashes simply changes 0xbf27 to 0xbf5c27 as a valid multi-byte character, where 0xbf5c is still considered a single quote, so addslashes cannot successfully intercept.
Of course, addslashes is not useless, it is used for single-byte string processing, multi-byte character or use mysql_real_escape_string.
Another example of get_magic_quotes_gpc in the PHP manual:
 
if (!get_magic_quotes_gpc()) { 
$lastname = addslashes($_POST[ ' lastname']); 
} else { 
$lastname = $_POST[ ' lastname']; 
} 

It is best to check $_POST['lastname'] if magic_quotes_gpc is already open.
Again, the difference between mysql_real_escape_string and mysql_escape_string:
Mysql_real_escape_string must be in the (PHP 4 > = 4.3.0, PHP 5). Otherwise, you just use mysql_escape_string. The difference between the two is:

Mysql_real_escape_string takes into account the current character set of the connection, while mysql_escape_string does not.

To summarize:

Addslashes () is forced;
Mysql_real_escape_string () determines the character set, but requires the PHP version;
Mysql_escape_string does not consider the current character set of the connection.

Related articles: