I am quite new to PHP, and with the help of a few tutorials have made this login system.
However I know its not as efficient and compact as it could be, also I am looking for ways to improve the security of this system. As I noticed when testing that If I simply changed the url from the login page, I could bypass the whole login process without having to login. I'm not really sure how I would go about fixing this, I tried creating session variables at the bottom of the script but not really sure if this is the way to go about it.
I would be very grateful for any feedback and if someone could help me improve this code, to make it more secure and maybe more efficient?
<?php
session_start();
if (isset($_POST['submit'])) {
require_once 'config.php';
$username = mysqli_real_escape_string($connect, $_POST['username']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
//Error handlers
//Check if inputs are empty
if (empty($username) || empty($password)) {
header("Location: ../index.php?login=empty");
exit();
} else {
$sql = "SELECT * FROM users WHERE username='$username'";
$search = mysqli_query($connect, $sql);
$validate = mysqli_num_rows($search);
if ($validate < 1) {
header("Location: ../index.php?login=error");
exit();
} else {
if ($row = mysqli_fetch_assoc($search)) {
//De-hashing the password
$hashcheck = password_verify($password, $row['password']);
if ($hashcheck == false) {
header("Location: ../index.php?login=error");
exit();
} elseif ($hashcheck == true) {
//Log in the user here
$_SESSION['u_id'] = $row['userid'];
$_SESSION['u_first'] = $row['firstname'];
$_SESSION['u_last'] = $row['lastname'];
$_SESSION['u_email'] = $row['email'];
$_SESSION['u_uid'] = $row['username'];
header("Location: ../home.php");
exit();
}
}
}
}
} else {
header("Location: ../index.php?login=error");
exit();
}
?>