In PHP, what are some considerations for updating user passwords to a more secure hashing algorithm like SHA512 while maintaining usability and security for existing users?

When updating user passwords to a more secure hashing algorithm like SHA512, it's important to consider how to handle existing users who have passwords hashed with a different algorithm. One approach is to check the password hash during the login process and rehash it with SHA512 if necessary. This ensures that existing users can still log in while gradually transitioning to the new hashing algorithm.

// Check if the user's password needs to be rehashed
if (password_needs_rehash($hashedPassword, PASSWORD_DEFAULT)) {
    // Rehash the password with SHA512
    $newHashedPassword = password_hash($password, PASSWORD_DEFAULT);

    // Update the user's password in the database
    // $userId is the user's ID, $newHashedPassword is the new hashed password
    // Update the 'password' field in the 'users' table where 'id' matches $userId
    $query = "UPDATE users SET password = ? WHERE id = ?";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$newHashedPassword, $userId]);
}