How can PHP be used to validate user input for passwords and login names?

When validating user input for passwords and login names in PHP, it is important to check for certain criteria such as length, special characters, and alphanumeric characters. This can be done using regular expressions and PHP functions like strlen() and preg_match(). By setting specific rules for passwords and login names, you can ensure that users are entering secure and valid information.

// Validate password
$password = $_POST['password'];

if(strlen($password) < 8 || !preg_match('/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/', $password)) {
    echo "Password must be at least 8 characters long and contain both letters and numbers.";
}

// Validate login name
$loginName = $_POST['login_name'];

if(strlen($loginName) < 5 || !preg_match('/^[a-zA-Z0-9_]+$/', $loginName)) {
    echo "Login name must be at least 5 characters long and contain only letters, numbers, and underscores.";
}