What is the purpose of using the password_needs_rehash function in PHP for storing password hashes securely in a user database?

When storing password hashes securely in a user database, it is important to periodically check if the hashing algorithm has been updated or if the cost factor needs to be increased for better security. The password_needs_rehash function in PHP allows you to easily check if a password hash needs to be rehashed with the current algorithm and options.

$password = "password123";

$options = [
    'cost' => 12,
];

$hash = password_hash($password, PASSWORD_BCRYPT, $options);

if (password_needs_rehash($hash, PASSWORD_BCRYPT, $options)) {
    $newHash = password_hash($password, PASSWORD_BCRYPT, $options);
    
    // Update the user's password hash in the database with $newHash
}