MOCKSTACKS
EN
Questions And Answers

More Tutorials









PHP Verifying a password against a hash


password_verify() is the built-in function provided (as of PHP 5.5) to verify the validity of a password against a known hash.

<?php
if (password_verify($plaintextPassword, $hashedPassword)) {
 echo 'Valid Password';
}
else {
 echo 'Invalid Password.';
}
?>


All supported hashing algorithms store information identifying which hash was used in the hash itself, so there is no need to indicate which algorithm you are using to encode the plaintext password with.

If the password_* functions are not available on your system (and you cannot use the compatibility pack linked in the remarks below) you can implement password verification with the crypt() function. Please note that specific precautions must be taken to avoid timing attacks.

<?php
// not guaranteed to maintain the same cryptographic strength of the full `password_hash()`
// implementation
if (CRYPT_BLOWFISH == 1) {
 // `crypt()` discards all characters beyond the salt length, so we can pass in
 // the full hashed password
 $hashedCheck = crypt($plaintextPassword, $hashedPassword);
 // this a basic constant-time comparison based on the full implementation used
 // in `password_hash()`
 $status = 0;
 for ($i=0; $i<strlen($hashedCheck); $i++) {
 $status |= (ord($hashedCheck[$i]) ^ ord($hashedPassword[$i]));
 }
 if ($status === 0) {
 echo 'Valid Password';
 }
 else {
 echo 'Invalid Password';
 }
}
?>


Conclusion

In this page (written and validated by ) you learned about PHP Verifying a password against a hash . What's Next? If you are interested in completing PHP tutorial, we encourage you simply to start here: PHP Tutorial.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.