PHP's addslashes()
and its SQL Injection Vulnerability
The PHP function addslashes()
, often used as a safeguard against SQL injection attacks, possesses limitations that can compromise security, particularly when dealing with multibyte characters. This article examines scenarios where addslashes()
fails to provide adequate protection.
Multibyte Character Encoding Issues
When input data includes multibyte characters, addslashes()
can incorrectly insert backslashes, disrupting the escape sequence and creating vulnerabilities. This occurs because addslashes()
might not accurately handle the encoding of multibyte characters.
Illustrative Example:
<code class="language-php">$input = "⭐' OR 1=1 --"; $escapedInput = addslashes($input); // Escapes as ⭐\' OR 1=1 --</code>
Here, the single quote following the multibyte star character remains unescaped, leaving the system open to SQL injection.
Encoding-Specific Vulnerabilities
The problem stems from addslashes()
's potential inability to correctly interpret multibyte character encodings such as EUC-JP or Shift-JIS. Certain character sequences in these encodings might contain a trailing 0x5c byte, misleading addslashes()
into creating a multibyte character instead of escaping the single quote.
Best Practices: Moving Beyond addslashes()
While addslashes()
offers some basic protection, it's not a reliable solution for preventing SQL injection, especially with multibyte character sets. For robust security, utilize more advanced techniques like mysqli_real_escape_string()
(for MySQLi) or, ideally, prepared statements. Prepared statements are the recommended approach for preventing SQL injection vulnerabilities.
The above is the detailed content of Is addslashes() in PHP Truly Safe Against SQL Injection, Even with Multibyte Characters?. For more information, please follow other related articles on the PHP Chinese website!