简朴的SQL注入示例
比方,A有一个银行网站。已为银行客户供应了一个收集界面,以检察其帐号和余额。您的银行网站运用http://example.com/get_account_details.php?account_id=102等网址从数据库中提取细致信息。
比方,get_account_details.php的代码,以下所示:
$accountId = $_GET['account_id']; $query = "SELECT accountNumber, balance FROM accounts WHERE accountId = $accountId";
客户accountId经由过程查询字符串作为account_id通报。与上面的Url一样,假如用户的帐户ID为102而且它在查询字符串中通报。Php剧本将建立以下所示的查询。
$query = "SELECT accountNumber, balance FROM accounts WHERE accountId = 102";
accountId 102猎取accountNumber和余额细致信息,并供应给客户。
相干引荐:《php教程》
我们假定另一个场景,智能客户已经由过程了account_id,就像0 OR 1=1查询字符串一样。如今会发作什么?PHP剧本将建立以下所示的查询并在数据库上实行。
$query = "SELECT accountNumber, balance FROM accounts WHERE accountId = 0 OR 1=1";
检察由剧本和数据库返回的效果建立的查询。您能够看到此查询返回了一切帐号和可用余额。
这称为SQL注入。这是一个简朴的体式格局,实在能够有许多方法来举行SQL注入。下面我们就来看一下怎样运用PHP MySQLi驱动程序和PHP PDO驱动程序防备SQL注入。
运用PHP-MySQLi驱动程序
能够运用PHP-MySQLi驱动程序预处理语句来防止这些范例的SQL注入。
PHP防备SQL注入的代码以下:
$accountId = $_GET['account_id']; if ($stmt = $mysqli->prepare('SELECT accountNumber, balance FROM accounts WHERE accountId = ?')) { $stmt->bind_param("s", $accountId); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { // do something here } $stmt->close(); }
运用PHP-PDO驱动程序
能够运用PHP-PDO驱动程序prepare语句来防止这些范例的SQL注入。
PHP处理上面的SQL注入题目的代码以下:
$accountId = $_GET['account_id']; if ($stmt = $pdo->prepare('SELECT accountNumber, balance FROM accounts WHERE accountId = :accountId')) { $stmt->execute(array('name' => $name)); foreach ($stmt as $row) { // do something here } $stmt->close(); }
以上就是php怎样防备sql注入的细致内容,更多请关注ki4网别的相干文章!