📅  最后修改于: 2023-12-03 15:27:40.508000             🧑  作者: Mango
你在写一个使用PHP的网站时,发现网站出现了SQL注入攻击,你该如何解决?
mysqli_real_escape_string
来过滤输入的数据$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql = "SELECT * FROM users WHERE username = '{$username}' AND password = '{$password}'";
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = ? AND password = ?');
$stmt->execute([$username, $password]);
$user = $stmt->fetch();
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
$stmt->execute(['username' => $username, 'password' => $password]);
$user = $stmt->fetch();
$user = DB::table('users')->where('username', $username)->where('password', $password)->get();
总之,要防止SQL注入,首先必须使用合适的方法来过滤输入的数据。其次,应当采取预处理语句来执行数据库操作,一定要避免直接拼接字符串来构造SQL语句。最后,使用ORM框架可以极大地简化整个过程,毕竟攻击者无法在一个完整的查询中进行注入。