Your users’ passwords are the lowest barrier of entry into your user account system. A weak password opens up the ability for bad actors to infiltrate your users accounts. So you have to help your users to protect themselves by enforcing minimum password requirements.
Creating Minimum Password Requirements
One way to enforce password security is by creating minimum requirements for passwords. You don’t want to do anything crazy here, as a lot of people have passwords that meet most minimum requirements and they’ll probably want to use them on your site as well.
I find having a minimum length, one lowercase letter, one uppercase letter, one number, and one special character is enough to force a strong password. And most users a used to this.
Creating The Password Validation Function In PHP
Let’s create a function that we can then use to validate a password string. The function looks like this:
<?php
/**
* Validate password
* Create a password with minimum requirements of one lowercase letter, one uppercase letter, one number, and one special character
* Website: https://scottsweb.dev/password-validation-with-php/
*/
function validate_password($password) {
// must be at least 6 characters
if (strlen($password) < 6) {
return false;
}
// must have one lowercase letter
if (!preg_match('/[a-z]/', $password)) {
return false;
}
// must have one uppercase letter
if (!preg_match('/[A-Z]/', $password)) {
return false;
}
// must have one digit
if (!preg_match('/\d/', $password)) {
return false;
}
// must have one special character
if (!preg_match('/[^a-zA-Z\d]/', $password)) {
return false;
}
// we're good
return true;
}
How To Use Password Validation Function
Now that we have our function, it’s time to use the password validation function on an actual string and test it out.
<?php
/**
* Scottsweb.dev
* https://scottsweb.dev/password-validation-with-php/
* Use password validation function
*/
// here we are statically creating a password, but this could come from $_POST data
$password = 'abc123';
// call the function to validate
if (validate_password($password)) {
echo 'Password is valid';
} else {
echo 'Password is not valid';
}
That’s it! You now have a function that you can use to enforce minimum password requirements on your users.
Hope this was helpful! If it was, please leave a comment on my video or subscribe to scottsweb.dev channel on YouTube.
Further Reading – Creating A User Registration System
A good place to use functionality like password validation is by creating a user registration or signup system. Watch the linked video / read the linked article to further your skills!
Also see how to validate a phone number with PHP.