Password Strength Checker Function - PHP
Shared by: devcanvas
php
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
|  | 
- 
Criteria: - Each key-value pair in the $criteriaarray represents a rule for a strong password. The key is a regular expression, and the value is a descriptive message for users.
 Example criteria: - Password must have at least 8 characters.
- Include at least one uppercase letter.
- Include at least one lowercase letter.
- Include at least one number.
- Include at least one special character (!, @, #, etc.).
 
- Each key-value pair in the 
- 
Filter Passed Rules: - The array_filterfunction iterates through the$criteriaarray, applying each regular expression to the password.
- If a match is found, the criterion passes and is added to the $passedarray.
 
- The 
- 
Return Feedback: - The function returns an associative array with two keys:
- strength: A score indicating how many rules the password passed (e.g., “4/5”).
- messages: A list of the rules the password satisfied.
 
 
- The function returns an associative array with two keys:
Example Output
When you run the function with the password P@ssw0rd123, here’s what the output looks like:
Array
(
    [strength] => 5/5
    [messages] => Array
        (
            [0] => At least 8 characters
            [1] => At least one uppercase letter
            [2] => At least one lowercase letter
            [3] => At least one number
            [4] => At least one special character
        )
)This indicates that the password satisfies all five criteria, making it very strong.
Customizing the Function
You can easily modify the function to adapt it to your security needs:
1. Add New Rules
For example, to ensure no spaces are allowed in the password:
'/^\S+$/' => "No spaces allowed",2. Provide Detailed Feedback
Instead of returning only the satisfied rules, you can return both passed and failed rules for a more comprehensive report.
3. Implement in Real-Time Validation
Use this function in conjunction with JavaScript to validate passwords dynamically on the frontend while keeping server-side validation as a fallback.
Tags
- “Password strength checker PHP”
- “Validate password strength PHP regex”
- “Strong password validation function PHP”
- “Secure password criteria PHP example”
- “PHP password security tips”