2

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
    }


    ?>
3
  • 2
    I can't see that you've used the password_hash function at all. What problem are you having specifically with it? You need to hash the password at registration, and then when you login, hash the user's input password and compare the two hashes using password_verify. Commented Jan 8, 2015 at 11:05
  • You might find this useful Commented Jan 8, 2015 at 11:46
  • Despite not using password_hash() - if you want to use it in the future, you will need php >= 5.5 running on the server to use it Commented Jan 8, 2015 at 17:12

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.