arukiri123 arukiri123 - 3 months ago 6
PHP Question

limiting login attempts of user

i need help for limiting login attempt of the user. this is my code.

$login = login($username, $password);
if($login === false) {
if($_COOKIE['login'] < 3){
$attempts = $_COOKIE['login'] + 1;
setcookie('login', $attempts, time()+60*10); //set the cookie for 10 minutes with the number of attempts stored
$errors[] = 'That username/password combination is incorrect!';
} else{
echo 'You are banned for 10 minutes. Try again later';
} else {
setcookie('login', 1, time()+60*10); //set the cookie for 10 minutes with the initial value of 1

} else {
$_SESSION['user_id'] = $login;
header('Location: ../../home.php');

it looks right for me but it just wont work. the user could still access his/her account even after attempting 3 login.


Use an SQL database, im currently working on a snippet of code, give me about an hour and ill throw an exampl up for you


$host = "";//Host name
$username = "";//MYSQL username
$password = "";//MYSQL password
$db_name = "";//Database name
$tbl_name = "";//Name of login table
$bl_name2 = "";//Name of table to store IP if attempt is incorrect

//connect to server and select database
$conn = new PDO('mysql:host='.$host.';dbname='.$db_name.'',$username, $password);
catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();}

//get users ip next, as this is for a log in, this example will show for username and pass also
$userPassword = $_POST['passwordfromform'];
$userUsername = $_POST['usernamefromform']

if(empty($userUsername) && empty($userPassword)){
die("You must enter a username and password");

//check for log in excess
SELECT * FROM ".$tbl_name2."
WHERE PostersIP = '".$userIP."'
$stmt = $db->query($checkSql);
$row_count = $stmt->rowCount();
if($rowcount >= 7){//change this number to reflect the nuber of login chances
die("You have tried to log in too many times");

//check to log in
$insertSql = "
SELECT * FROM ".$tbl_name."
WHERE USERNAME = '".$userUsername."'
AND PASSWORD = '".$userPassword."'";

//execute check query
$result = $conn->query($insertSql);
if($result != false){
echo "Username and Password were correct!";//link to correct page
INSERT INTO ".$tbl_name2."
(PostersIP) VALUES 
    $result2 = $conn->query($incorrectSql);
     if($result2 != false){
          die("You entered an invalid username or password, your attempt has been stored.");
die("Error inserting data");

I did not test this live, so there may be a few flaws, however i commented it pretty well for ya. you do need a second table to store user submission ips. this is a VERY messy way to do this. Im very sure there are better ways to do it, but theres my 10 minute solution :)