Login system with password_hash [duplicate]

淺唱寂寞╮ 提交于 2020-01-26 03:58:05

问题


I am trying to login users that are added by an admin, but when I press login, nothing happens, just a blank page with the header login.php. Here is the code I use to add users:

    <?php 
    include "connection.php";
 ?>

<!DOCTYPE html>
<html>
<head>
    <title>Add students</title>
    <link rel="stylesheet" type="text/css" href="boosttrap.min.css">
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
            <form action="adduser.php" method="POST">
                <div>
                    <h2>
                        Username will be generated automatically
                    </h2>
<br/>
                    <label>Password</label>
                    <input type="password" name="s_password" class="form-control" placeholder="Enter new passowrd">        
<br/>
                    <label>Name</label>
                    <input type="text" name="s_name" class="form-control" placeholder="Enter name">
<br/>
                    <label>Surname</label>
                    <input type="text" name="s_surname" class="form-control" placeholder="Enter surname">
<br/>
                    <label>Date of birth</label>
                    <input type="date" name="s_dob" class="form-control" placeholder="Enter Date of birth">
<br/>
                    <label>Year group</label>
                    <select name ="s_yeargroup">
                        <option  selected = "true" disabled="disabled"> Select one from below...</option>
                            <option value=1 >7</option>
                            <option value=2> 8</option>
                            <option value=3> 9</option>
                            <option value=4> 10</option>
                            <option value=5> 11</option>
                    </select>
<br/>
                    <button type="sumbit" name="btnAddUser" class="float" value ="Login">Create New User</button>
                </div>
            </form>
            <a href="../logout.php">Logout</a>
</body>


<?php 

if(isset($_POST["btnAddUser"])){

        $hashed_password = password_hash($_POST['s_password'], PASSWORD_DEFAULT);
        $name = $_POST["s_name"];
        $surname = $_POST["s_surname"];
        $dob = $_POST["s_dob"];
        $yeargroup = $_POST["s_yeargroup"];

$usernamenew = substr($name, 0, 1);
$usernamenew1 = substr($surname, 0, 4);
$usernamenew3= $usernamenew.$usernamenew1;
$sql = "INSERT INTO tbluser (Username, Password, Role) VALUES ('$usernamenew3', '$hashed_password', 'Student')"; 
if(!mysqli_query($conn,$sql))
 {
    echo "Error with Username or password";
 }
 else 
 {
    echo "Username and password created successfully. The username is ".$usernamenew3.".";
 }
$sql4= "SELECT ID FROM tbluser WHERE Username = '$usernamenew3'";
$result1= mysqli_query($conn,$sql4);
$row= mysqli_fetch_assoc($result1);
$userid=$row['ID'];

$sql1 = "INSERT INTO student (name, surname, dob, yeargroup_id, tbluser_ID) VALUES ('$name','$surname','$dob','$yeargroup','$userid')";
if(!mysqli_query($conn,$sql1))
 {
    echo "Error with Student info";
 }
 else 
 {
    echo " \r\nStudent has been added successfully.";
}
}
?>

And here is my code that I use to login users

<?php
session_start();
require_once "connection.php";
$message = "";
$role = "";
if(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)
    {
        while ($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');    
                }
                else
                    echo "Role is not recognised";
            }   
        }
    }
}

If anyone could find my mistake, I would appreciate it. Thank you My database in case you need it.


回答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.

<?php
if(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');    
            }
            else
                echo "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.




回答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.



来源:https://stackoverflow.com/questions/59672859/login-system-with-password-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!