PHP password validation

PHP password validation

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

The Logic Trap in Password Validation

Looking at the provided PHP validation logic, the immediate red flag isn't a syntax error; it's a fundamental logical flaw in how the elseif chain handles the confirmation password check. The code attempts to validate the strength of the password first, but it fails to account for the scenario where the passwords do not match.

The specific issue lies within the block handling password and confirm password validation:

if(!empty($_POST["password"]) && ($_POST["password"] == $_POST["cpassword"])) {
    // ... strength checks ...
    if (strlen($_POST["password"]) <= '8') { /* error */ }
    elseif(!preg_match("#[0-9]+#", $password)) { /* error */ }
    elseif(!preg_match("#[A-Z]+#", $password)) { /* error */ }
    elseif(!preg_match("#[a-z]+#", $password)) { /* error */ }
    else {
        $cpasswordErr = "Please Check You've Entered Or Confirmed Your Password!";
    }
}

The condition if(!empty($_POST["password"]) && ($_POST["password"] == $_POST["cpassword"])) creates a strict gate. If the passwords do not match, the entire block is skipped entirely. Consequently, $cpasswordErr remains empty, and no validation message is displayed for the mismatch. This means if a user enters "Password123" as the password and "WrongPass456" as the confirmation, the script silently ignores the mismatch because it never enters the if block where the error variable is set.

To fix this, you must separate the equality check from the strength checks. The standard pattern for this validation requires three distinct conditions:

  1. Ensure both fields are not empty.
  2. Ensure the strings match exactly.
  3. If they match, run the complexity rules (length, numbers, casing).

Here is the corrected logic structure:

// Step 1 & 2: Check if inputs exist and if they match
if (!empty($_POST["password"]) && !empty($_POST["cpassword"])) {
    $password = test_input($_POST["password"]);
    $cpassword = test_input($_POST["cpassword"]);

    // If passwords do not match, set error immediately
    if ($password !== $cpassword) {
        $cpasswordErr = "The entered password and confirm password do not match.";
    } else {
        // Only run strength checks if they match
        $isWeakPassword = false;

        if (strlen($password) <= 8) {
            $isWeakPassword = true;
        }
        
        // Regex checks for complexity. Note: preg_match returns 1 on match, 0 otherwise.
        if (!$isWeakPassword && !preg_match("#[0-9]+#", $password)) {
            $isWeakPassword = true;
        }
        if (!$isWeakPassword && !preg_match("#[A-Z]+#", $password)) {
            $isWeakPassword = true;
        }
        if (!$isWeakPassword && !preg_match("#[a-z]+#", $password)) {
            $isWeakPassword = true;
        }

        if ($isWeakPassword) {
            $cpasswordErr = "Your password must contain at least 8 characters, one number, and one capital letter.";
        } else {
            // Success case
        }
    }
}

Security Considerations for test_input

There is a secondary concern regarding the test_input function provided in the source code. The function applies htmlspecialchars():

function test_input($data) {
     $data = trim($data);
     $data = stripslashes($data);
     $data = htmlspecialchars($data); // <--- Problem here for passwords
     return $data;
}

Applying htmlspecialchars() to password fields is a critical mistake. This function converts special characters like < and > into HTML entities (&lt;, &gt;). If a user intends to use symbols like ! or @ in their password, this function will corrupt the data before it is stored in the database. Furthermore, storing an HTML-escaped version of a password makes hashing difficult because you cannot reliably reverse the process or compare it against a hash later without knowing exactly which entities were applied.

For registration forms, you should never sanitize passwords with htmlspecialchars() at the input stage. Instead, rely on server-side libraries like password_hash() to handle security. The test_input function should be removed from password fields entirely or restricted strictly to string trimming and stripping slashes if absolutely necessary for other logic (though even stripslashes is often unnecessary in modern PHP contexts).

Moving Beyond Regex

While the regex patterns #[0-9]+#, #[A-Z]+#, and #[a-z]+# are functional for basic validation, they are not sufficient for robust security. They check for the presence of character types but do not enforce minimum counts (e.g., requiring two numbers or one special character).

Modern development frameworks handle this complexity much better than raw PHP regex. If you are working in a Laravel project, the built-in Rule system is significantly more concise and maintainable. You can define complex validation rules directly on the request:

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'password' => ['required', 'min:8', 'max:20', 'confirmed', 'regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/'],
]);

However, if you must stick to vanilla PHP for legacy reasons or specific hosting environments, fixing the logical flow of the if/elseif statements and removing HTML escaping from password fields are the mandatory first steps.

Our network