如何防止PHP中的SQL注入?

102 阅读1分钟

内容来自 DOC https://q.houxu6.top/?s=如何防止PHP中的SQL注入?

如果没有对用户输入进行任何修改就插入到SQL查询中,那么应用程序就会容易受到SQL注入攻击,就像以下示例中的那样:

$unsafe\_variable = $\_POST['user\_input']; 

mysql\_query("INSERT INTO `table` (`column`) VALUES ('$unsafe\_variable')");

这是因为用户可以输入类似于“value'); DROP TABLE table;--”的内容,查询就变成了:

INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')

为了防止这种情况发生,可以采取以下措施:

  1. 使用预处理语句(Prepared Statements)或参数化查询(Parameterized Queries),这样可以将用户输入作为参数传递给查询,而不是将其直接嵌入到查询中。例如:
$unsafe_variable = $_POST['user_input']; 

mysql_query("INSERT INTO `table` (`column`) VALUES (?)", $unsafe_variable);
  1. 对用户输入进行验证和过滤,确保输入的数据符合预期的格式和类型。可以使用正则表达式或其他验证方法来实现。例如:
$unsafe_variable = $_POST['user_input']; 

if (preg_match('/^[a-zA-Z0-9]+$/', $unsafe_variable)) {
    mysql_query("INSERT INTO `table` (`column`) VALUES (?)", $unsafe_variable);
} else {
    // 处理无效输入的情况
}