Puneet Chawla Puneet Chawla - 5 months ago 52
PHP Question

Compare password in WordPress always return false

I want to insert new user in WordPress by coding and then compare username &
password. I tried to insert user name and password in two ways.

1

Insert new user code (Table - wp_users)

$email = $_POST['txtEmail'];
$userName = $_POST['txtUserName'];//Sahil
$password = $_POST['txtPassword'];//1212
$hash_value = password_hash($password, PASSWORD_BCRYPT);
$user_id = wp_create_user( $userName, $hash_value, $email);


2

Tried to insert password in another way

$settings = array('cost' => 10, 'salt' => 'rSq.2M7Ikc.QPhVtYlp1Nu');
$hash_value = password_hash($password, PASSWORD_BCRYPT, $settings);
$user_id = wp_create_user( $userName, $hash_value, $email);


I didn't add code to check username & email exists in table. Above code is working properly and new user is being added in wp_users table and password is being stored in hash format. Ex. $P$BgynwP/kZuQu5p/SAU/dTMA19sbJs3/

I tried to compare it by two function, but it always return false.

1

$userName = $_POST['txtUserName'];//Sahil
$password = $_POST['txtPassword'];//1212

$user = get_user_by( 'login', $userName );
$result = wp_check_password( $password, $user->user_pass, $user->ID);
if($result){
echo 'Correct';
}else{
echo 'Wrong'; //Always return wrong
}


2

$userName = $_POST['txtUserName'];//Sahil
$password = $_POST['txtPassword'];//1212
$user = get_user_by( 'login', $userName );
$isPasswordCorrect = password_verify($password, $user->user_pass);
if($isPasswordCorrect){
echo 'Correct';
}else{
echo 'Wrong'; //Always return wrong.
}


Also tried -

var_dump(password_verify($password, $user->user_pass));


But it still return false.

Let me know, If there is any mistake in my code while comparing password or technique is wrong to do this.

Thanks

Answer

You muse use the plain password in wp_create_user, not a hash.

Comments