YouTip LogoYouTip

Php Password_Verify

## PHP password_verify() Function The `password_verify()` function in PHP is used to verify whether a given plain-text password matches a stored cryptographic hash. It is a crucial component of PHP's native password hashing API, designed to prevent security vulnerabilities such as timing attacks. ### Version Requirements * **PHP 5 >= 5.5.0** * **PHP 7** * **PHP 8** --- ### Syntax ```php bool password_verify ( string $password , string $hash ) ``` #### Parameters * **`password`**: The plain-text password provided by the user (e.g., from a login form). * **`hash`**: The hashed password string against which to verify. This hash must be created using the [`password_hash()`](https://www.php.net/manual/en/function.password-hash.php) function. #### Return Value * Returns `true` if the password and hash match. * Returns `false` if they do not match. --- ### Code Example The following example demonstrates how to verify a plain-text password against a pre-calculated hash. ```php ``` #### Output ```text Password is valid! ``` --- ### Key Considerations & Best Practices 1. **Timing Attack Protection** `password_verify()` is safe against timing attacks. It uses a constant-time comparison algorithm to ensure that the time taken to reject an incorrect password does not leak information about how close the guess was to the actual password. 2. **No Need to Manually Extract Salts** The `$hash` string generated by `password_hash()` contains information about the algorithm, cost factor, and salt used during hashing. `password_verify()` automatically extracts these parameters from the hash string, so you do not need to store or manage salts separately in your database. 3. **Handling Algorithm Upgrades** Over time, hardware becomes faster, and older hashing algorithms or cost factors may become insecure. It is highly recommended to pair `password_verify()` with `password_needs_rehash()`. If a user logs in successfully but the hash was generated using an outdated algorithm or cost, you can rehash the password and update the database seamlessly: ```php if (password_verify($password, $storedHash)) { // Check if the hash needs to be updated to a stronger algorithm/cost if (password_needs_rehash($storedHash, PASSWORD_DEFAULT)) { $newHash = password_hash($password, PASSWORD_DEFAULT); // Update $newHash in your database for this user } // Proceed with logging the user in } ```
← Obj CssstyledeclarationReact Lists And Keys β†’