Home > Article > Backend Development > mysql_real_escape_string() vs. addslashes(): Which Escaping Function Provides Better SQL Injection Protection?
In developing web applications, preventing SQL injection attacks is crucial. While addslashes() is a commonly used function for escaping characters, it falls short in certain scenarios. The mysql_real_escape_string() function specifically addresses these limitations, enhancing SQL injection protection.
mysql_real_escape_string() escapes a broader range of characters (x00, n, r, , ', ", and x1a) compared to addslashes() which only escapes three characters (', and NUL). This comprehensive coverage ensures that characters that could potentially be exploited for SQL injection are properly escaped, minimizing vulnerabilities.
Despite using addslashes(), a webapp remains vulnerable to SQL injection if it exclusively relies on this function for character escaping. One scenario where addslashes() fails is when a malicious input contains double quotes ("). These quotes can terminate the already quoted string, allowing the attacker to inject arbitrary SQL statements.
For example:
<code class="php">$username = addslashes($_POST['username']); $sql = "SELECT * FROM users WHERE username='$username'";</code>
If the user input is "John' OR 1='1", addslashes() will only escape the single quote ('), resulting in the following SQL statement:
<code class="sql">SELECT * FROM users WHERE username='John\' OR 1=\'1\'</code>
The double quote (") is not escaped, allowing the attacker to terminate the quoted string and append additional SQL logic. As a result, the query will return all users instead of just John, potentially compromising sensitive information.
While addslashes() provides basic character escaping for SQL injection protection, it is insufficient to completely eliminate vulnerabilities. mysql_real_escape_string() overcomes this limitation by escaping a wider range of characters, addressing scenarios where addslashes() fails. By using mysql_real_escape_string() or adopting parameterized queries as a superior alternative, web developers can significantly enhance the security of their applications against SQL injection attacks.
The above is the detailed content of mysql_real_escape_string() vs. addslashes(): Which Escaping Function Provides Better SQL Injection Protection?. For more information, please follow other related articles on the PHP Chinese website!