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;
}