简单的SQL注入示例
例如,A有一个银行网站。您已经向银行客户提供了一个网络界面,以查看其帐号和余额。您的银行网站使用 http://example.com/get_account_details.php?account_id=102等网址从数据库中获取详细信息。 例如 get_account_details.php有如下代码。
<br /><br /><br /> $accountId = $_GET['account_id'];<br /><br /><br /> $query = "SELECT accountNumber, balance FROM accounts WHERE accountId = $accountId";
1
2
|
$accountId
=
$_GET
[
'account_id'
]
;
$query
=
"SELECT accountNumber, balance FROM accounts WHERE accountId = $accountId"
;
|
<br /><br /><br /> $query = "SELECT accountNumber, balance FROM accounts WHERE accountId = 102";
1
|
$query
=
"SELECT accountNumber, balance FROM accounts WHERE accountId = 102"
;
|
0 OR 1=1
in query string. What will be happened now? The PHP script will create a query like below and executed on the database.
<br /><br /><br /> $query = "SELECT accountNumber, balance FROM accounts WHERE accountId = 0 OR 1=1";
1
|
$query
=
"SELECT accountNumber, balance FROM accounts WHERE accountId = 0 OR 1=1"
;
|
#1. Using PHP-MySQLi Driver
You can use PHP-MySQLi driver prepared statements to avoid these type of SQL injections. Use below PHP code which will prevent SQL injection.
<br /><br /><br /> $accountId = $_GET['account_id'];</p><br /><br /> <p>if ($stmt = $mysqli->prepare('SELECT accountNumber, balance FROM accounts WHERE accountId = ?')) {</p><br /><br /> <p> $stmt->bind_param("s", $accountId);</p><br /><br /> <p> $stmt->execute();</p><br /><br /> <p> $result = $stmt->get_result();</p><br /><br /> <p> while ($row = $result->fetch_assoc()) {<br /><br /><br /> // do something here<br /><br /><br /> }</p><br /><br /> <p> $stmt->close();<br /><br /><br /> }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
$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
(
)
;
}
|
#2. Using PHP-PDO Driver
You can use PHP-PDO driver prepare statements to avoid these type of SQL injections. Use below PHP code which will resolve above SQL injections.
<br /><br /><br /> $accountId = $_GET['account_id'];</p><br /><br /> <p>if ($stmt = $pdo->prepare('SELECT accountNumber, balance FROM accounts WHERE accountId = :accountId')) {</p><br /><br /> <p> $stmt->execute(array('name' => $name));</p><br /><br /> <p> foreach ($stmt as $row) {<br /><br /><br /> // do something here<br /><br /><br /> }</p><br /><br /> <p> $stmt->close();<br /><br /><br /> }
1
2
3
4
5
6
7
8
9
10
11
12
|
$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
(
)
;
}
|