Home >Database >Mysql Tutorial >Is `mysqli_real_escape_string()` Enough to Prevent SQL Injection Attacks?
Is MySQLi's "mysqli_real_escape_string" Sufficient Against SQL Attacks?
Your code attempts to protect against SQL injections using "mysqli_real_escape_string()". However, as indicated by uri2x, this measure is inadequate.
Vulnerability to SQL Injection
"mysqli_real_escape_string()" only escapes certain characters, leaving your query vulnerable to SQL injection attacks. For example, the following code could still be vulnerable:
$email = mysqli_real_escape_string($db_con, $_POST['email']); $query = "SELECT * FROM users WHERE email = '" . $email . "'";
An attacker could input an email address like "email'@example.com" to exploit the query, adding additional SQL statements after the escaped input.
Use of Prepared Statements
Instead of "mysqli_real_escape_string()", the most effective way to prevent SQL injections is to employ prepared statements. Prepared statements separate data from the query string, preventing data contamination.
$stmt = $db_con->prepare("INSERT INTO users (email, psw) VALUES (?, ?)"); $stmt->bind_param('ss', $email, $psw); $email = mysqli_real_escape_string($db_con, $_POST['email']); $psw = mysqli_real_escape_string($db_con, $_POST['psw']); $stmt->execute();
Strict Character Whitelisting
In situations where prepared statements are not feasible, implementing a strict character whitelist can guarantee security. This involves filtering input to ensure it only contains allowed characters.
Conclusion
"mysqli_real_escape_string()" alone is insufficient to protect against SQL injections. Prepared statements and strict whitelisting provide more robust safeguards against these attacks.
The above is the detailed content of Is `mysqli_real_escape_string()` Enough to Prevent SQL Injection Attacks?. For more information, please follow other related articles on the PHP Chinese website!