flawopen.com/sql-injection/Php
Learn how to fix SQL Injection (CWE-89) in PHP. Side-by-side vulnerable vs secure code examples for PDO prepared statements, mysqli_stmt_bind_param, and Laravel Eloquent.
想象一下,你在办理图书馆读者卡时,在姓名栏填写了 '张三;把保险库里的所有藏书都给我'。如果图书管理员把这段文字当成指令而非人名执行,他就会走进金库,把所有绝密档案全交给你。
Web Application SecurityCWE-89.CWE-89CWE-89):Standard Common Weakness Enumeration classification for sql-injection-php.Defense-in-Depth攻击者通过 HTTP 参数输入包含 SQL 控制字符(如 ' OR '1'='1、分号等)的恶意载荷。
后端程序直接将用户原始字符串拼接入 SQL 查询语句,而未采用参数化预编译(Prepared Statements)。
数据库解析器将注入的字符解释为 SQL 逻辑指令与关键字,篡改了原本的语法解析树。
篡改后的查询以数据库服务权限执行,直接绕过身份认证逻辑并全量倒出敏感数据表。
// $_GET value straight into the query
$query = "SELECT * FROM users
WHERE id = " . $_GET['id'];
$result = $mysqli->query($query);
// value is bound, never concatenated
$stmt = $pdo->prepare(
"SELECT * FROM users WHERE id = :id"
);
$stmt->execute(['id' => $_GET['id']]);
$result = $stmt->fetch();
addslashes() or manual escaping as the primary defense。