How To Limit The Number Of Login Attempt Using PHP Part 2(PHP Functionality)

How to limit the number of login attempt using PHP part 2(PHP functionality) image

In previous post we design the login form, so finally  implement PHP code

// LOG USER IN
	if (isset($_POST['login_btn'])) {
	$email = esc($_POST['email']);
	$password = esc($_POST['password']); 									 				
	$time=time()-60;
	$ip_address=getIpAddr();
	$check_login_result= "SELECT count(*) as total_count from login_log WHERE try_time>$time and email='$email'";
	$check_result = mysqli_query($conn, $check_login_result);
	$check_login_row = mysqli_fetch_assoc($check_result);
	$total_count=$check_login_row['total_count'];
	if($total_count==6){
	array_push($errors, 'You have too many login attempts failed.');
	 $deactivate_account=  "UPDATE users SET  status = 0 WHERE email='$email'";
        $result = mysqli_query($conn, $deactivate_account);
        array_push($errors, 'For a security reason your account was deactivated. Contact the account Administrator at info@g3techdesign.com');
	}else{	    		
	       if (empty($email)) {array_push($errors, "Username required"); }
		if (empty($password)) {array_push($errors, "Password required"); }
		// attempt login if no errors on form
		if (count($errors) == 0) {
			$password = md5($password); // encrypt password
			$sql = "SELECT * FROM users WHERE (email='$email' OR username='$email') AND password='$password' LIMIT 1";
            $result = mysqli_query($conn, $sql);
			if (mysqli_num_rows($result) > 0) {
				$row = mysqli_fetch_assoc($result);
				$verified = $row['verified'];
				$status = $row['status'];
				$email = $row['email'];
				$created_at = $row['created_at'];
				$verification_at = date("F j, Y ", strtotime($created_at));
				$created_at = strtotime($created_at);
				$created_at = date('M d Y',$created_at);
				if($status == 1){
				if($verified == 1){
				// get id of created user
				$reg_user_id = $row['id']; 
                // put logged in user into session array
				$_SESSION['user'] = getUserById($reg_user_id); 
                  if($reg_user_id)
                  {
                  if(!empty($_POST["remember"]))
                  {
                  setcookie ("emaillogin", $_POST["email"], time() + (1*2629440));/*10 * 365 * 24 * 60 * 60*/
                  setcookie ("password", $_POST["password"], time() + (1*2629440));/*10 * 365 * 24 * 60 * 60*/
                  setcookie ("remember", $_POST["remember"], time() + (1*2629440));/*10 * 365 * 24 * 60 * 60*/
                  }
                  else
                  {
                  if(isset($_COOKIE["emaillogin"]))
                  {
                  setcookie ("emaillogin", "");
                  }
                  if(isset($_COOKIE["password"]))
                  {
                  setcookie ("password", "");
                  }
                  if(isset($_COOKIE["remember"]))
                  {
                  setcookie ("remember", "");
                  }
		 }
	  }
     // Gets data from URL parameters.
                    if(isset($_GET['add_location'])) {
                        add_location();
                    }
                    function add_location(){
                        $lat = $_GET['lat'];
                        $lng = $_GET['lng'];
                        $description =$_GET['description'];
                        // Inserts new row with place data.
                        $query = sprintf("INSERT INTO users "
                            . " (latitude, longitude, description) "
                            . " VALUES ('%s', '%s', '%s');",
                            mysqli_real_escape_string($con,$lat),
                            mysqli_real_escape_string($con,$lng),
                            mysqli_real_escape_string($con,$description));
                        $result = mysqli_query($con,$query);
                    }
		          $update=  "UPDATE users SET lastloginprevious=lastlogin, lastlogin = now(), latitude = 45.7811111, longitude =45.7811111  WHERE email='$email'";
		          //".$_POST['lat']." ".$_POST['lng']." 
                  $result = mysqli_query($conn, $update);
                  $email_post = esc($_POST['email']);
                  $delete=  "DELETE FROM login_log WHERE email='$email_post'";
                  $result = mysqli_query($conn, $delete);
				// if user is admin, redirect to admin area
				if ( in_array($_SESSION['user']['role'], ["Admin", "Author"])) {
					$_SESSION['message'] = "<i class='fas fa-check-circle fa-2x'></i> Welcome " .$_SESSION['user']['firstname']. " ".$_SESSION['user']['lastname']. ", you are now logged in as Admin/Author";
					// redirect to admin area
					header('location: ' . BASE_URL . 'admin/dashboard.php');
					exit(0);
				} else {
                    	$_SESSION['message'] ="<div class='input-container'>
                       <i class='fas fa-check-circle fa-2x'></i> Welcome " .$_SESSION['user']['firstname']. " ".$_SESSION['user']['lastname']. ", you are now logged in as USER. You can explore member contents. </div>";
					// redirect to public area
					header('location: '. BASE_URL . 'channel.php');				
					exit(0);
				}	
				}else{
					array_push($errors, '<i class="fas fa-times-circle fa-2x"></i> We are sorry for the inconvenience. This account has not been verified yet. A verification link was sent to ' .$email. ' on ' .$verification_at );
				}
				}else{
				array_push($errors, '<i class="fas fa-times-circle fa-2x"></i> We are sorry for the inconvenience. This account was deactivated. Contact the account Administrator at info@g3techdesign.com to solve a problem' );
	                      }							
								
			}else {					
			$total_count++;
			$rem_attm=6-$total_count;
			if($rem_attm==0){
				array_push($errors,'<i class="fas fa-times-circle fa-2x"></i> Too many login attempts failed . Please try to login after 60 seconds. Do not attempt to login before a time window. Your account will be deactivated. OR <a href=\password-recovery/enter_email><font color="blue">Reset Your Password</font></a>');
				array_push($errors,"<div id='status' class='message' style='background-color:transparent;border:0px solid transparent;'></div>");
			}else{
				array_push($errors, '<i class="fas fa-times-circle fa-2x"></i> Your Email or Password does not matched. You submitted wrong credentials. Try Again or <a href=\password-recovery/enter_email><font color="blue">Reset Your Password</font></a><br/><center><i style=color:red><sup>*</sup>'.$rem_attm.' attempts remaining.</i></center>');
			}
			$try_time=time();
			$insert ="INSERT INTO login_log(email,ip_address,try_time) values('$email','$ip_address','$try_time')";
			mysqli_query($conn, $insert);
				
			}
        }
       }
}

if you wandering what is the getIpAddress() function is identify a user based on the Ip address of the device connected to count the post view(check out count the visitor when the visit the post )

 function getIpAddr(){
    if (!empty($_SERVER['HTTP_CLIENT_IP'])){
       $ipAddr=$_SERVER['HTTP_CLIENT_IP'];
    }elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
       $ipAddr=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
       $ipAddr=$_SERVER['REMOTE_ADDR'];
    }
   return $ipAddr;
}
	// escape value from form
	function esc(String $value)
	{	
		// bring the global db connect object into function
		global $conn;

		$val = trim($value); // remove empty space sorrounding string
		$val = mysqli_real_escape_string($conn, $value);

		return $val;
	}

 

Leave a non public comment how to improve it.



Characters Remaining

We are sorry for your bad experiance. Leave a non public comment how to improve it.



Characters Remaining

Related Posts (12)

Getting User Device Location and Updating Database image

Getting User Device Location and Updating Database

Author image
By JOHN Mon Feb 19, 2024 at 12:31 PM (3 months ago)
Updated On Sat Mar 09, 2024 at 07:59 AM (2 months ago)

Read More »
How to create a custom archive page template on your website layout image

How to create a custom archive page template on your website layout

Author image
By JOHN Thu Nov 17, 2022 at 08:00 AM (2 years ago)
Updated On Thu Jan 05, 2023 at 06:24 PM (one year ago)

Read More »
Test the video layout design(Upload and Store video to MySQL Database with PHP) image

Test the video layout design(Upload and Store video to MySQL Database with PHP)

Author image
By JOHN Sat Nov 05, 2022 at 05:15 PM (2 years ago)
Updated On Wed Nov 09, 2022 at 06:39 PM (2 years ago)

Read More »
How to set the expiry period for a reset password link. image

How to set the expiry period for a reset password link.

Author image
By JOHN Mon Oct 10, 2022 at 05:31 AM (2 years ago)
Updated On Tue Nov 08, 2022 at 07:53 PM (2 years ago)

Read More »
Send A verification email when a new user registered  image

Send A verification email when a new user registered

Author image
By JOHN Tue Dec 07, 2021 at 04:53 PM (2 years ago)
Updated On Tue Nov 08, 2022 at 06:58 AM (2 years ago)

DGDFH

Read More »
How to Send Verification link when a new user register image

How to Send Verification link when a new user register

Author image
By JOHN Fri Oct 15, 2021 at 07:49 AM (3 years ago)
Updated On Fri Nov 04, 2022 at 05:00 PM (2 years ago)

This tutorial teaches you to build an email verification script from scratch

Read More »
How to limit the number of login attempts  image

How to limit the number of login attempts

Author image
By JOHN Sat Oct 31, 2020 at 10:19 PM (4 years ago)
Updated On Wed Nov 09, 2022 at 04:38 PM (2 years ago)

It is one of a security mechanism to restrict an authorized user from access the systems and locked the account if it's necessary. In this tutorial we will create a simple login system to demonstrate the implementation using PHP and MySQL. Let's digest it...

Read More »
Download file using PHP image

Download file using PHP

Author image
By MEWDED Wed Sep 02, 2020 at 10:04 AM (4 years ago)
Updated On Sat Nov 12, 2022 at 09:10 AM (2 years ago)

Short explanation 

Read More »
Inactive user enforce to login (SESSION expired) or Limmit the resource image

Inactive user enforce to login (SESSION expired) or Limmit the resource

Author image
By MEWDED Tue Sep 01, 2020 at 04:24 AM (4 years ago)
Updated On Sat Nov 12, 2022 at 09:35 AM (2 years ago)

Quick description

Read More »
How to count page viewers based on the IP Address of the device image

How to count page viewers based on the IP Address of the device

Author image
By MEWDED Thu Aug 27, 2020 at 04:37 PM (4 years ago)
Updated On Sat Nov 12, 2022 at 06:57 PM (2 years ago)

Hi, today we will walk you through how to implement to count the page viewers base on IP address like Youtube or Facebook 

Read More »
Pagination in PHP image

Pagination in PHP

Author image
By MEWDED Fri Aug 14, 2020 at 02:58 PM (4 years ago)
Updated On Fri Nov 04, 2022 at 03:08 PM (2 years ago)

Hi there ????, 

TODAY we are walking ????‍?? together to show you how to implement pagination in PHP

Read More »
Author Title image

Author Title

Author image
By JOHN Mon Jul 13, 2020 at 04:19 AM (4 years ago)
Updated On Fri Nov 04, 2022 at 03:08 PM (2 years ago)

Author description

Read More »

Share this on

Search


Archives

No archives data found yet in 2025.

No archives data found in 2016.

Find Us on Facebook

Subscribe for new updates




Back to Top