-1
此代碼是從另一篇文章在Notice: Undefined offset: 0 in採取它被指出存在SQL注入漏洞。這個代碼是脆弱的,它如何被利用,以及如何安全呢?這段代碼如何引入SQL注入漏洞?
<?php
include("config.php");
function getAllVotes($id)
{
$votes = array();
$q = "SELECT * FROM entries WHERE id = $id";
$r = mysql_query($q);
if(mysql_num_rows($r)==1)//id found in the table
{
$row = mysql_fetch_assoc($r);
$votes[0] = $row['votes_up'];
$votes[1] = $row['votes_down'];
}
return $votes;
}
function getEffectiveVotes($id)
{
$votes = getAllVotes($id);
$effectiveVote = $votes[0] - $votes[1]; //ERROR THROWN HERE
return $effectiveVote;
}
$id = $_POST['id'];
$action = $_POST['action'];
//get the current votes
$cur_votes = getAllVotes($id);
//ok, now update the votes
if($action=='vote_up') //voting up
{
$votes_up = $cur_votes[0]+1; //AND ERROR THROWN HERE
$q = "UPDATE threads SET votes_up = $votes_up WHERE id = $id";
}
elseif($action=='vote_down')
{
$votes_down = $cur_votes[1]+1;
$q = "UPDATE threads SET votes_down = $votes_down WHERE id = $id";
}
$r = mysql_query($q);
if($r)
{
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote." votes";
}
elseif(!$r) //voting failed
{
echo "Failed!";
}
?>
這樣的:'WHERE ID = $ id'。如果我要傳遞「$ id = 17; DROP TABLE條目」會怎麼樣?你可以閱讀更多關於sql注入[這裏](http://bobby-tables.com/)。你可以通過使用[prepared statements。](https://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html)來避免它。還有其他技術,比如鑄造$ id如果你知道它應該總是一個整數,則爲整數。 –
請參閱[母親的利用](http://imgs.xkcd.com/comics/exploits_of_a_mom.png) – user3791372
做得好@devlincarnate。我在答案中忘記了「準備好的陳述」的名字。此外,提供替代解決方案(鑄造)。 – andrewgu