AndroLauncher
AndroLauncher

Reputation: 11

How to apply the bcrypt on my php

DBOperations.php

public function userLogin($username, $pass){
    $password = $pass;
    $stmt = $this->conn->prepare("SELECT s_id FROM students WHERE s_id = ? AND password = ?");
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $stmt->store_result(); 
    return $stmt->num_rows > 0; 
}

userLogin.php

<?php 

require_once '../include/DbOperations.php';

$response = array(); 

if($_SERVER['REQUEST_METHOD']=='POST'){
    if(isset($_POST['username']) and isset($_POST['password'])){
        $db = new DbOperations(); 

        if($db->userLogin($_POST['username'], $_POST['password'])){
            $user = $db->getUserByUsername($_POST['username']);
            $response['error'] = false; 
            $response['id'] = $user['id'];
            $response['firstname'] = $user['firstname'];
            $response['lastname'] = $user['lastname'];
            $response['middlename'] = $user['middlename'];
            $response['s_id'] = $user['s_id'];
        }else{
            $response['error'] = true; 
            $response['message'] = "Invalid username or password";          
        }

    }else{
        $response['error'] = true; 
        $response['message'] = "Required fields are missing";
    }
}

echo json_encode($response);

I already try the "password_hash($pass, PASSWORD_BCRYPT)" still it doesn't work. I search and I try them apply on it but still it doesn't work

Upvotes: 0

Views: 25

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46650

Presuming you're storing the hash from password_hash() in the database.

Select the password for the username, then check it with password_verify().

<?php
public function userLogin($username, $pass) {
    $stmt = $this->conn->prepare("SELECT password FROM students WHERE s_id = ? LIMIT 1");
    $stmt->bind_param("s", $username);
    $stmt->execute();

    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
       return false; 
    }

    $row = $result->fetch_array(MYSQLI_ASSOC);

    return password_verify($pass, $row['password']);
}

Upvotes: 1

Related Questions