Frage

Working on my first project which requires secure authentication. My hosting is still on PHP 5.3.27 so I'm using the password_hash() compatibility patch found here. My issue is that return password_hash($password, PASSWORD_BCRYPT, array('cost'=>$cost)); errors out stating that $password must be a string. Why is it not a string? I don't even know where to start debugging.

HTML which gets the password

<form method='post' action='register.php' name='loginform'>
    <label for="inputpass">Password</label>
    <input type="password" class="form-control" id="inputpass" placeholder="Enter a password">
</form>

contents of register.php

<?php

require 'validate.php';

$password = $_POST['password'];
var_dump(validations::generate_hash($password));

?>

contents of validate.php *password.php is the 5.3 compatibility patch for password_hash()*

<?php

require 'plugins/password.php';

class validations {

    function generate_hash($password){

        $cost = 11;

        return password_hash($password, PASSWORD_BCRYPT, array('cost'=>$cost));

    }

    function validate_pw($password, $hash){

        return crypt($password, $hash)==$hash;

    }   
}

?>
War es hilfreich?

Lösung

In your code, $password is not a string but the null value¹. That's because $_POST does not have key named password², which in turn happens because you do not have an input element with name="password in your form.

Adding a name attribute will make things work:

<input type="password" name="password" class="form-control" id="inputpass"
       placeholder="Enter a password">

¹ You can verify this with var_dump($password).

² This will cause PHP to emit an E_NOTICE message at the line you are making the assignment. Turning error_reporting to the maximum with error_reporting(E_ALL); would make this message appear.

Andere Tipps

I was reading your code and yo have some errors in the HTML form.

First you must to use " instead ' in attribute. Second you must set a name attribute in the input tag.

In the other hand I was trying to run your code in my computer but unfortuantely I don have the PHP version 5.5 to run password_hash.

Also remember you must set your methods as follows :

public static function generate_hash($password)
{
    $cost = 11;
    return password_hash($password, PASSWORD_BCRYPT, array('cost' => $cost));
}

because your var_dump() is :

var_dump(validations::generate_hash($password));

I suggest too try the next line of code to validate your $_POST

$password = isset($_POST['password']) ? $_POST['password'] : '';

I think thats all.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top