wundidajah
wundidajah

Reputation: 177

How to use bcrypt for user data with PHP/MySQL/JSON

I'm currently developing an android application and using PHP/MySQL/JSON for the user registration and the login procedere. Now i want to use bcyrpt for hashing the user data. I am totally new to PHP and read a lot of tutorials for hashing, but i do not found any proper tutorial for my PHP skript which i can use. I tried the password_hash() function, but it won't work.

Can you please give me advice how i can use bcrypt with my files.

Those are my PHP files:

LOGIN

<?php

require("config.inc.php");

if (!empty($_POST)) {

    $query = " 
            SELECT 
                id, 
                username, 
                password
            FROM users 
            WHERE 
                username = :username 
        ";

    $query_params = array(
        ':username' => $_POST['username']
    );

    try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {

        $response["success"] = 0;
        $response["message"] = "Database Error1. Please Try Again!";
        die(json_encode($response));

    }

    $validated_info = false;

    $row = $stmt->fetch();
    if ($row) {

        if ($_POST['password'] === $row['password']) {
            $login_ok = true;
        }
    }

    if ($login_ok) {
        $response["success"] = 1;
        $response["message"] = "Login successful!";
        die(json_encode($response));
    } else {
        $response["success"] = 0;
        $response["message"] = "Invalid Credentials!";
        die(json_encode($response));
    }
} else {
?>
        <h1>Login</h1> 
        <form action="login.php" method="post"> 
            Username:<br /> 
            <input type="text" name="username" placeholder="username" /> 
            <br /><br /> 
            Password:<br /> 
            <input type="password" name="password" placeholder="password" value="" /> 
            <br /><br /> 
            <input type="submit" value="Login" /> 
        </form> 
        <a href="register.php">Register</a>
    <?php
}

?> 

REGISTER

<?php

    require("config.inc.php");

    if (!empty($_POST)) {

        if (empty($_POST['username']) || empty($_POST['password'])) {

            $response["success"] = 0;
            $response["message"] = "Please Enter Both a Username and Password.";

            die(json_encode($response));
        }

        $query        = " SELECT 1 FROM users WHERE username = :user";
        $query_params = array(
            ':user' => $_POST['username']
        );

        try {
            $stmt   = $db->prepare($query);
            $result = $stmt->execute($query_params);
        }
        catch (PDOException $ex) {

            $response["success"] = 0;
            $response["message"] = "Database Error1. Please Try Again!";
            die(json_encode($response));
        }

        $row = $stmt->fetch();
        if ($row) {

            $response["success"] = 0;
            $response["message"] = "I'm sorry, this username is already in use";
            die(json_encode($response));
        }

        $query = "INSERT INTO users ( username, password ) VALUES ( :user, :pass ) ";

        $query_params = array(
            ':user' => $_POST['username'],
            ':pass' => $_POST['password']
        );

        try {
            $stmt   = $db->prepare($query);
            $result = $stmt->execute($query_params);
        }
        catch (PDOException $ex) {

            $response["success"] = 0;
            $response["message"] = "Database Error2. Please Try Again!";
            die(json_encode($response));
        }

        $response["success"] = 1;
        $response["message"] = "Username Successfully Added!";
        echo json_encode($response);

    } else {
    ?>
        <h1>Register</h1> 
        <form action="register.php" method="post"> 
            Username:<br /> 
            <input type="text" name="username" value="" /> 
            <br /><br /> 
            Password:<br /> 
            <input type="password" name="password" value="" /> 
            <br /><br /> 
            <input type="submit" value="Register New User" /> 
        </form>
        <?php
    }


    ?>

Upvotes: 2

Views: 668

Answers (1)

martinstoeckli
martinstoeckli

Reputation: 24081

In your register script you should not store the password directly, instead call the password_hash() function and store its result:

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($_POST['password'], PASSWORD_DEFAULT);

In the login script you can get the password-hash from the database as you did, but instead of comparing it with the entered password, you have to call the password_verify() function:

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($_POST['password'], $existingHashFromDb);

Upvotes: 1

Related Questions