m

全干工程师

PHP如何正确阻止SQL注入

SQL注入是一个很大安全隐患、程序会被拖库、程序源码泄漏、等一系列严重问题。在PHP代码中我们如何保证程序不被SQL注入呢,首先我们应该使用(PDO)扩展或者(mysqi)扩展, 使用其中的参数绑定或者值绑定功能。这样一来,攻击者就不可能注入恶意SQL。

1. 使用PDO:

//参数绑定
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute(array('name' => $name));

foreach ($stmt as $row) {
    // do something with $row
}

//绑定值
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = ?');

$stmt->bindValue(1, $name, PDO::PARAM_STR);

foreach ($stmt as $row) {
    // do something with $row
}
//实际都是参数绑定,只是方法不一样

2. 使用mysqli:

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}

留言