• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

PHP password hash and verify help??

220061

Coder
Hello I'm trying to do a password_has and password verify for my project. I'm trying to make my project safer step by step. I have already put a pashword hash in my code and that works as you see:
1637593367763.png
but I can't seem to get it to verify. it either says password incorrect or I can't login at all no matter if I use the hashed account or the other dummy accounts with the password showing in the db. what am i doing wrong?

signup.php
PHP:
<?php
// this code is not really that safe try to make it safer aftehr watchign the tutorial
    session_start();
    include_once "config.php";
    $fname = mysqli_real_escape_string($conn , $_POST['fname']);
    $lname = mysqli_real_escape_string($conn , $_POST['lname']);
    $email = mysqli_real_escape_string($conn , $_POST['email']);
    $password = mysqli_real_escape_string($conn , $_POST['password']);
    $password = password_hash($password, PASSWORD_DEFAULT);

    if(!empty($fname) && !empty($lname) && !empty($email) && !empty($password)){
        //checking if user email is valid or not
        if(filter_var($email, FILTER_VALIDATE_EMAIL)){ // check if email is valid
            //check if email already exist in de db or not
            $sql = mysqli_query($conn, "SELECT email FROM users WHERE email = '{$email}'");
            if(mysqli_num_rows($sql) > 0){ // if email already exist
                echo "$email - This email already exist";
            }else{
                //lets check if user uploud file or not
                if(isset($_FILES['image'])) { // if file is uploaded
                    //$_FILES returns us an array with the file name, file type , error file sizen , tmp_name
                    $img_name = $_FILES['image']['name']; //getting user uploaded img name
                    $tmp_name = $_FILES['image']['tmp_name']; // this temporary name is used to save/move file into our folder

                    //explode image and get the image last extension as an png jpg
                    $img_explode =  explode('.', $img_name);
                    $img_ext = end($img_explode); // get the extension from a user uplouden img file

                    $extensions = ['png', 'jpeg', 'jpg']; // valid extensions en we hebben ze gestored in een array
                    if(in_array($img_ext, $extensions) === true){ // if user img uplouded matches with any of the valif images extensions
                        $time = time(); // this will return us the current time
                                        // we need this because when a user uplouds a picture in to our folder we rename user file with current time
                                        //so all the image files will habe a unique name
                        //let's move the user uploaded img to our particular folder
                        // we don't uploud user uplouded file in the db we just save the file url thier.
                        //actual file will be saved in our particulair folder
                        //current time will be added the name of user uplouded the img so if the user uplouded 2 different img with the same name then the name of a particulair img will be unique with adding time.
                        $new_img_name = $time.$img_name;
                        if(move_uploaded_file($tmp_name, "images/" .$new_img_name)){ //if user uploud img uploud to our folder succesfully
                            $status = "Active now"; //  once user signed up then his status will be active now)
                            $random_id = rand(time(), 10000000); //create random id for users
                            //inser all user data inside table
                            $sql2 = mysqli_query($conn, "INSERT INTO users (unique_id, fname, lname, email, password, img, status)
                                                VALUES ({$random_id}, '{$fname}','{$lname}', '{$email}', '{$password}', '{$new_img_name}', '{$status}')");
                            if($sql2){ //if these data inserted
                                $sql3 = mysqli_query($conn, "SELECT * FROM users WHERE email = '{$email}'");
                                if(mysqli_fetch_assoc($sql3) > 0){
                                    $row = mysqli_fetch_assoc($sql3);
                                    $_SESSION['unique_id'] = $row['unique_id']; //using this session we use user_id in a other php file
                                    echo "success";
                                }
                            }else{
                                echo "Something went wrong!";
                            }
                        }
                        
                    }else{
                        echo "Please select an Image file - jpeg, jpg, png!";
                    }

                }else{
                    echo "please select a profile picture!";
                }
            }
        }else{
            echo "$email - This is not a valid email!";
        }

    }else{
        echo "All input fields are required!";
    }

login.php
PHP:
<?php
//code is not safe yet
    session_start();
    include_once "config.php";
    $email = mysqli_real_escape_string($conn , $_POST['email']);
    $password = mysqli_real_escape_string($conn , $_POST['password']);
  
    if(!empty($email) && !empty($password)){
        //check if users email and password match with the one in de db
        $sql = mysqli_query($conn, "SELECT * FROM users WHERE email = '$email' AND password = '$password'");
        if(password_verify($password, $row["password"])) 
                     { 
                          //return true; 
                          if(mysqli_num_rows($sql) > 0){// if the email and pass are correct
                            $row = mysqli_fetch_assoc($sql);
                            $status = "Active now";
                            $sql2 = mysqli_query($conn, "UPDATE users SET status = '{$status}' WHERE unique_id = {$row['unique_id']}");
                            if($sql2){
                                $_SESSION['unique_id'] = $row['unique_id']; //using this session we use user_id in a other php file
                                echo "success";
                            }
                        }else{
                            echo "Email or password is incorrect!";
                        }
                          
                     } 
                     else 
                     { 
                          //return false; 
                          echo '<script>alert("Wrong User Details")</script>'; 
                     } 
        
    }else{
        echo "All input fields are required!";
    }
?>

the html code
HTML:
<?php
    session_start();
    if(isset($_SESSION['unique_id'])){ //if user is logged in
        header("location: users.php");
    }
?>
<?php include_once "header.php";?>
<body>
    <div class="wrapper">
        <!--Dit is een login form -->
        <section class="form login">
            <header>Realtime chat app</header>
            <form action="#" autocomplete="off">
                <div class="error-txt"></div>
                <div class="name-details">
                    <div class="field input">
                        <label>Email</label>
                        <input type="text" name="email" placeholder="Enter your email">
                    </div>
                    <div class="field input">
                        <label>Password</label>
                        <input type="password" name="password" placeholder="Enter your password">
                        <!--functie die ervoor zorgd dat je je wachtwoord kan zien door op oogje te klikken-->
                        <i class="fa fa-eye" aria-hidden="true"></i>
                    </div>
                    <div class="field button">
                        <input type="submit" value="Continue to chat">
                    </div>
                </div>
            </form>
            <div class="link">Nog geen account? <a href="index.php">Regristreer nu!</a></div>
        </section>
    </div>
    <script src="javascript/pass-show-hide.js"></script>
    <script src="javascript/login.js"></script>
</body>
</html>

and this is my javascript code
JavaScript:
//code voor de signup form tags
const form = document.querySelector(".login form"),
continueBtn = form.querySelector(".button input"),
errorText = form.querySelector(".error-txt");

form.onsubmit = (e)=>{
    e.preventDefault(); //preventing from form submit
}
continueBtn.onclick = ()=>{
    //lets start ajax
    let xhr = new XMLHttpRequest(); //creating XML object
    xhr.open("POST", "php/login.php", true);
    xhr.onload = ()=>{
        if(xhr.readyState === XMLHttpRequest.DONE){
            //shows response of the passed url
            if(xhr.status === 200){
                let data = xhr.response;
                console.log(data);
                 if(data == "success"){
                     location.href = "users.php";
                 }else{
                     errorText.textContent =  data;
                     errorText.style.display = "block";
                    
                 }
            }
        }
    }
    //sending form data through ajax to php
    let formData = new FormData(form); // creating new formdata object
    xhr.send(formData); //sending formdata to php
}

any help would be appreciated
 

Mutiny

Active Coder
In signup.php you appear to be storing the hashed password in the database, but when you do the check in login.php you appear to be querying the database for the unencrypted password. You should hash the password in login.php, then find the record in the database where the email address and hashed password match.

Also, looking at the screenshot you posted some passwords appear to be stored unhashed in the database, so you'll want to ensure all passwords are hashed in the database as if you're testing with two different sets of data it will cause problems as well.
 

220061

Coder
In signup.php you appear to be storing the hashed password in the database, but when you do the check in login.php you appear to be querying the database for the unencrypted password. You should hash the password in login.php, then find the record in the database where the email address and hashed password match.

Also, looking at the screenshot you posted some passwords appear to be stored unhashed in the database, so you'll want to ensure all passwords are hashed in the database as if you're testing with two different sets of data it will cause problems as well.
maybe I'm not really understanding but I have tried to do password hash in login.php however then it won't hash and it will show the password in the db.
login.php
PHP:
<?php
//code is not safe yet
    session_start();
    include_once "config.php";
    $email = mysqli_real_escape_string($conn , $_POST['email']);
    $password = mysqli_real_escape_string($conn , $_POST['password']);
    $passwordhash = password_hash($password, PASSWORD_DEFAULT);

    if(!empty($email) && !empty($password)){
        //check if users email and password match with the one in de db
        $sql = mysqli_query($conn, "SELECT * FROM users WHERE email = '$email' AND password = '$password'");
        if(password_verify($password, $passwordhash)) 
                     { 
                          //return true; 
                          if(mysqli_num_rows($sql) > 0){// if the email and pass are correct
                            $row = mysqli_fetch_assoc($sql);
                            $status = "Active now";
                            $sql2 = mysqli_query($conn, "UPDATE users SET status = '{$status}' WHERE unique_id = {$row['unique_id']}");
                            if($sql2){
                                $_SESSION['unique_id'] = $row['unique_id']; //using this session we use user_id in a other php file
                                echo "success";
                            }
                        }else{
                            echo "Email or password is incorrect!";
                        }
                          
                     } 
                     else 
                     { 
                          //return false; 
                          echo '<script>alert("Wrong User Details")</script>'; 
                     } 
        
    }else{
        echo "All input fields are required!";
    }
?>

and this is then my db as you can see it doesn't hash.
1637653832741.png
 

220061

Coder
update: it still doesn't work but right now the errors are
object(mysqli_result)#3 (5) { ["current_field"]=> int(0) ["field_count"]=> int(2) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) } string(3) "lol" object(mysqli_result)#3 (5) { ["current_field"]=> int(0) ["field_count"]=> int(2) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) } <br /> <b>Warning</b>: password_verify() expects parameter 2 to be string, object given in <b>C:\xampp\htdocs\chatting\php\login.php</b> on line <b>20</b><br /> <script>alert("Wrong User Details")</script>
PHP:
<?php
//code is not safe yet
    session_start();
    include_once "config.php";
    $email = mysqli_real_escape_string($conn , $_POST['email']);
    $password = mysqli_real_escape_string($conn , $_POST['password']);
    //$passwordindb = password_hash($password, PASSWORD_DEFAULT);

    if(!empty($email) && !empty($password)){
        //check if users email and password match with the one in de db
        
        $sql2 = mysqli_query($conn, "SELECT * FROM users");
        $row = mysqli_fetch_assoc($sql2);
        $dbcheck = $conn->query("SELECT email, password FROM users WHERE email = '$email'");
        var_dump($dbcheck);
        $sql = mysqli_query($conn, "SELECT * FROM users WHERE email = '$email' AND password = '$password'");
      
        var_dump($password);
        var_dump($dbcheck);
        if(password_verify($password, $dbcheck)) 
        { 
                         var_dump($password);
                         var_dump($dbcheck);
                          //return true; 
                          if(mysqli_num_rows($sql) > 0){// if the email and pass are correct
                            $status = "Active now";
                            $sql2 = mysqli_query($conn, "UPDATE users SET status = '{$status}' WHERE unique_id = {$row['unique_id']}");
                                if($sql2){
                                    $_SESSION['unique_id'] = $row['unique_id']; //using this session we use user_id in a other php file
                                    echo "success";
                                }
                            }else{
                                echo "Email or password is incorrect!";
                            }
                          
        } 
        else 
        { 
        //return false; 
        echo '<script>alert("Wrong User Details")</script>'; 
        } 
        
    }else{
        echo "All input fields are required!";
    }
?>
 

220061

Coder
already also tried asking on stack overflow but I'm still not seeing it
PHP:
<?php
//code is not safe yet
    session_start();
    include_once "config.php";
    $email = mysqli_real_escape_string($conn , $_POST['email']);
    $password = mysqli_real_escape_string($conn , $_POST['password']);
    //$passwordindb = password_hash($password, PASSWORD_DEFAULT);

    if(!empty($email) && !empty($password)){
        //check if users email and password match with the one in de db
        
        //$sql3 = mysqli_query($conn, "SELECT * FROM users");
        //$row = mysqli_fetch_assoc($sql3);
        //$passdbcheck = $conn->query("SELECT email, password FROM users WHERE email = '$email'");

        //$sql = mysqli_query($conn, "SELECT * FROM users WHERE email = '$email' AND password = '$password'");
        $sql =  "SELECT * FROM users WHERE email = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $email );
        $stmt->execute();
        $data = $stmt->fetch_all(mysqli_fetch_assoc);
        foreach ($data as $datas) {
            printf("%s (%s)\n", $datas["email"], $datas["password"]);
            var_dump($datas);
        }

        if(password_verify($password, $data)) 
        { 
            
                          //return true; 
                          if(mysqli_num_rows($sql) > 0){// if the email and pass are correct
                            $status = "Active now";
                            $sql2 = "UPDATE users SET status = ? WHERE unique_id = ?";
                            $stmt = $conn->prepare($sql2);
                            $stmt->bind_param("ss", $status, $row['unique_id']);
                            $stmt->execute();
                            $data = $stmt->get_result()->fetch_all();
                            var_dump($data);
                                if($sql2){
                                    $_SESSION['unique_id'] = $row['unique_id']; //using this session we use user_id in a other php file
                                    echo "success";
                                }
                            }else{
                                echo "Email or password is incorrect!";
                            }
                          
        } 
        else 
        { 
        //return false; 
        echo '<script>alert("Wrong User Details")</script>'; 
        } 
        
    }else{
        echo "All input fields are required!";
    }
?>
 

Top