Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP User Authentication Adding Authentication to Your Application Password Hashing

Oliver Bird
Oliver Bird
57,653 Points

Changing a users password - " Bummer! Make the $newPassword and $verifyNewPassword are the same."

I've tested this locally and it seems to work.

Not sure if I have misunderstood, however I don't see any mention of the $verifyNewPassword variable in the initial question.

index.php
<?php

function newPasswordValid($userPassword, $currPassword, $newPassword, $confirmNewPassword) {
    //add code here

  if (password_verify($currPassword, $userPassword)) {
           if ($newPassword === $confirmNewPassword) {
      try {
          $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
          return $hashedPassword;

         } catch (\Exception $e) {
            return false;
   }
}
}
}

1 Answer

Hello, look at the documentation. Any of these methods doesn't return exception, so try catch is useless. Your solution returns null if if doesn't valid.

My opinion: I think better solution would be return null if passwords are not valid, otherwise return hash. Then I would use return type ?string and php forces me type return null, so you can easily avoid this.

http://php.net/manual/en/function.password-hash.php http://php.net/manual/en/function.password-verify.php

I did it like this:

<?php

function newPasswordValid($userPassword, $currPassword, $newPassword, $confirmNewPassword) {
    //add code here
    if (password_verify($currPassword, $userPassword) && $newPassword === $confirmNewPassword) {
        return password_hash($newPassword, PASSWORD_DEFAULT);
    }

    return false;
}
Oliver Bird
Oliver Bird
57,653 Points

Thank you. Makes more sense now!