简体   繁体   中英

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

You can used wp_authenticate_username_password()

Authenticate a user, confirming the username and password are valid

$email = $_POST['txtEmail'];
$userName = $_POST['txtUserName'];//Sahil
$password = $_POST['txtPassword'];//1212
$check = wp_authenticate_username_password( NULL, $userName , $password );

You can then simply check the result with

if(is_wp_error( $check ))
{
  echo 'Wrong'; 
}
else
{
  echo 'Correct';
}

Create user In WordPress wp_create_user() Password automatic save to database no need convert password_hash

wp_create_user( "Sahil", "1212", "Sahil@gmail.com" );

您必须在wp_create_user使用普通密码,而不是哈希。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM