Password Validator Using Regex (PHP)


When building a secure web application, password validation is essential. While many tutorials teach “strong passwords,” they often overlook the importance of blocking characters that hackers commonly use in exploits like SQL injection or XSS.

In this tutorial, we’ll create a PHP function that validates passwords, allows most characters, but blocks potentially dangerous ones.


Why Block Certain Characters?

Hackers often use characters like:

< > ' " ; ` \

…to manipulate your system. By restricting these in passwords, you reduce the risk of exploits, while still allowing users to create strong and memorable passwords.


PHP Password Validation Function

<?php
function validate_password($password) {
    // Regex breakdown:
    // (?=.*[a-z])   -> at least one lowercase letter
    // (?=.*[A-Z])   -> at least one uppercase letter
    // (?=.*\d)      -> at least one number
    // [^<>\'"`;\\]  -> block dangerous characters
    // {8,64}        -> length between 8 and 64 characters
    $pattern = '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^<>\'"`;\\\\]{8,64}$/';

    return preg_match($pattern, $password) === 1;
}

// Example usage
$passwords = [
    "SafePass123!",
    "Bad<Pass1",
    "Another$Good1"
];

foreach ($passwords as $pwd) {
    if (validate_password($pwd)) {
        echo "'$pwd' is valid.<br>";
    } else {
        echo "'$pwd' is invalid.<br>";
    }
}
?>

How It Works

  1. Require complexity
    • At least one lowercase letter [a-z]
    • At least one uppercase letter [A-Z]
    • At least one number \d
  2. Block risky characters
    • [^<>\'";\]denies< > ‘ ” ; `
  3. Control password length
    • {8,64} ensures passwords aren’t too short or unreasonably long

Output Example

If you run the example above, you’ll get:

'SafePass123!' is valid.
'Bad<Pass1' is invalid.
'Another$Good1' is valid.

This gives users freedom while keeping your system safer.


Conclusion

This PHP-only solution is easy to embed in any project:

  • Minimal code
  • Strong enough for most apps
  • Blocks characters that could be exploited

You can also expand this by requiring at least one special symbol or customizing blocked characters for your own needs.

Loading...