What are the best practices for handling password validation and comparison in PHP registration scripts?

When handling password validation and comparison in PHP registration scripts, it is important to ensure that passwords are securely hashed before storing them in the database. Additionally, passwords should be validated against certain criteria such as minimum length, presence of uppercase and lowercase letters, numbers, and special characters. Finally, when comparing passwords during login, always use a secure password hashing algorithm like bcrypt to verify the entered password against the hashed password stored in the database.

// Hashing the password before storing it in the database
$password = $_POST['password'];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// Validating password against criteria
if(strlen($password) < 8 || !preg_match("#[0-9]+#", $password) || !preg_match("#[a-z]+#", $password) || !preg_match("#[A-Z]+#", $password) || !preg_match("#\W+#", $password)) {
    // Password does not meet criteria
    echo "Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one number, and one special character.";
} else {
    // Password meets criteria, proceed with registration
}

// Comparing passwords during login using bcrypt
$entered_password = $_POST['password'];
$stored_hashed_password = ""; // Retrieve hashed password from database
if(password_verify($entered_password, $stored_hashed_password)) {
    // Passwords match, allow login
} else {
    // Passwords do not match, deny login
}