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
Release: 2024-12-02 16:09:14
Original
532 people have browsed it

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'";
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template