Home >Database >Mysql Tutorial >Does `addslashes()` Really Protect Against SQL Injection, and Why Should You Use `mysql_real_escape_string()` Instead?

Does `addslashes()` Really Protect Against SQL Injection, and Why Should You Use `mysql_real_escape_string()` Instead?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-15 19:34:17293browse

Does `addslashes()` Really Protect Against SQL Injection, and Why Should You Use `mysql_real_escape_string()` Instead?

addslashes() vs. mysql_real_escape_string() in Preventing SQL Injection

While often touted as a safer alternative to addslashes(), mysql_real_escape_string() remains the recommended method for preventing SQL injection vulnerabilities in PHP applications. Understanding the limitations of addslashes() is key to building robust security.

Consider this: an SQL query, relying on addslashes() for user input sanitization, encounters a string containing a single quote ('). addslashes() might incorrectly identify this quote as part of a multibyte character, leaving the query susceptible to injection.

An attacker can exploit this by appending a hyphen (-) or a similar character that terminates a multibyte sequence in certain Unicode encodings (like ISO-8859-1, but not UTF-8). This tricks addslashes() into treating the single quote as part of a valid multibyte character, bypassing the escape mechanism and allowing malicious code execution.

The vulnerability is encoding-specific. UTF-8, a widely used Unicode encoding, is generally safe from this particular attack because it doesn't use the same multibyte termination character.

For optimal SQL injection protection, always prioritize mysql_real_escape_string() over addslashes(). Supplement this with application-level input validation and the use of prepared statements for database interactions. By acknowledging addslashes()'s weaknesses and implementing these best practices, developers can significantly reduce the risk of SQL injection attacks.

The above is the detailed content of Does `addslashes()` Really Protect Against SQL Injection, and Why Should You Use `mysql_real_escape_string()` Instead?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn