Home >Database >Mysql Tutorial >Is `mysql_real_escape_string()` Truly Secure Against SQL Injection?

Is `mysql_real_escape_string()` Truly Secure Against SQL Injection?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-02 16:09:14476browse

Is `mysql_real_escape_string()` Truly Secure Against SQL Injection?

Addressing the Flaws of mysql_real_escape_string()

Despite its widespread use in PHP applications, some have raised concerns regarding the security vulnerabilities of mysql_real_escape_string(). This function is designed to prevent SQL injection attacks by escaping special characters in user input.

Is mysql_real_escape_string() Totally Inadequate?

The MySQL C API documentation acknowledges a potential issue with mysql_real_escape_string(). It suggests avoiding the use of SET NAMES/SET CHARACTER SET statements to change the connection's character set. Instead, the function mysql_set_character_set() should be called prior to using mysql_real_escape_string().

Proof Code

The PHP function mysql_set_charset() modifies the character set used by mysql_real_escape_string(). This is illustrated in the following code snippet:

<?php
// Connect to MySQL and select the database
$link = mysqli_connect("localhost", "user", "password", "database");

// Set the character set for the connection
mysql_set_charset($link, "utf8");

// Escape the input using mysql_real_escape_string()
$escaped_input = mysql_real_escape_string($link, $input);

// Use the escaped input in a SQL query
$query = "SELECT * FROM table WHERE field = '$escaped_input'";

By following this approach, the character set used by mysql_real_escape_string() can be explicitly set, ensuring that special characters are escaped correctly.

The above is the detailed content of Is `mysql_real_escape_string()` Truly Secure Against SQL Injection?. 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