I wish to ask if the code written below has any holes (probably it will be useful for someone else). This code checks, by IP and by userid
, if more than 5 attempts within the last 5 minutes were made to login. Every attempt to log in is stored in the history
table (MySQL).
The history
table is needed only for the purpose of CAPTCHA displaying. ENGINE=InnoDB is chosen for history table.
No indexes were put on Time
or userid
or remote_addr
.
Any suggestions about optimization?
$query1="SELECT id FROM history
WHERE (Time>date_sub(now(), interval 5 minute))
AND remote_addr='" . ip2long($_SERVER['REMOTE_ADDR']) . "' limit 6";
//limit 6 is for performance, 6+ means 6, we only care if it less than 5
$result1=mysql_query($query1);
//so we know mysql_num_rows($result1)
$query2="SELECT id FROM history
WHERE (Time>date_sub(now(), interval 5 minute))
AND userid='" . $userid . "' limit 6";
//limit 6 is for performance, 6+ means 6, we only care if it less than 5
$result2=mysql_query($query2);
//so we know mysql_num_rows($result2)
$attempts=0; // we want to set up $attempts=maximum of
// (mysql_num_rows($result1), mysql_num_rows($result2))
if($result1) {
$attempts=mysql_num_rows($result1);
}
if($result2 && $attempts<mysql_num_rows($result2)) {
$attempts=mysql_num_rows($result2);
}
// if $attempts is more than 5, then CAPTCHA should be displayed,
// if less then it should not