Login System With Password_hash
Solution 1:
Your use of password_hash() and password_verify() is fine.
You're only selecting the Username and Password columns from the table. So $row["Role"] won't be set and none of the if conditions will succeed. You should be getting the error Role is not recognized as a result.
Change it to:
$stmt=$conn->prepare("SELECT Username, Password, Role, ID FROM tbluser WHERE Username = ? ");
Also, add else statements so you know which if condition is failing when the login fails.
<?phpif(isset($_POST["btnLogin"]))
{
$password = $_POST["password"];
$stmt=$conn->prepare("SELECT Username, Password FROM tbluser WHERE Username = ? ");
$stmt-> bind_param("s",$_POST["username"]);
$stmt->execute();
$result = $stmt->get_result();
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
if(password_verify($password, $row["Password"]))
{
if($row["Role"] == "Admin")
{
$_SESSION['AdminUser'] = $row["Username"];
$_SESSION['adminid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: admin/admin.php');
}
elseif($row["Role"] == "Teacher")
{
$_SESSION['ProfUser'] = $row["Username"];
$_SESSION['teacherid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: teacher/prof.php');
}
elseif($row["Role"] == "Student")
{
$_SESSION['StudentUser'] = $row["Username"];
$_SESSION['studentid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: student/student.php');
}
elseecho"Role is not recognised";
} else {
echo"Password incorrect";
}
} else {
echo"Username not found";
}
} else {
echo"Form not submitted correctly";
}
You don't need a while loop when fetching the row, since usernames are unique; there's just one row.
Solution 2:
From the password_hash documentation, password_hash with PASSWORD_BCRYPT, produces a string 60 characters long and other algorithms might produce even longer. Your Password field in the database is only 45 characters.
As per recommendation from the documentation, you should increase the field size to 255.
Post a Comment for "Login System With Password_hash"