In: Computer Science
Write a PHP program that checks the elements of a string array named $Passwords. Use regular expressions to test whether each element is a strong password.
For this exercise, a strong password must have at least one number, one lowercase letter, one uppercase letter, no spaces, and at least one character that is not a letter or number. (Hint: Use the [^0-9A-Za-z] character class.) The string should also be between 8 and 16 characters long.
The $Passwords array should contain at least 10 elements, and at least six of the elements should fail. Ensure that one entry fails each of the five regular expression tests and that at least one fails because of the length. Display whether each password in the $Passwords array was strong enough, and display the test or tests that a password failed if it is not strong enough. Save the script as PasswordStrength.php.
Code:
<?php
$password = array("alex@God","ALEX@GOD1","alex@god1","alex
@god1","alexGod1","alex@G1","alex@GOD1","ALEXgod@123","ALEXgod@2","alex@GOD1");
for ($x = 0; $x <10; $x++) {
$pass = $password[$x];
echo $pass. " ";
echo number($pass);
echo lower($pass);
echo upper($pass);
echo noword($pass);
echo space($pass);
echo len($pass);
echo "\n";
}
function number($pass){
if (!preg_match("/^(?=(.*[\d]){1,})/",$pass)) {
return "Atleast 1 digit required.";
}
return;
}
function lower($pass){
if (!preg_match("/^(?=(.*[a-z]){1,})/",$pass)) {
return "Atleast 1 lower case required.";
}
return;
}
function upper($pass){
if (!preg_match("/^(?=(.*[A-Z]){1,})/",$pass)) {
return "Atleast 1 upper case required.";
}
return;
}
function noword($pass){
if (!preg_match("/^(?=(.*[\W]){1,})/",$pass)) {
return "Atleast 1 special character required.";
}
return;
}
function space($pass){
if (!preg_match("/^(?!.*\s)/",$pass)) {
return "No space allowed.";
}
return;
}
function len($pass){
if(strlen($pass)>16){
return "The length should be less than 16.";
}
if(strlen($pass)<8){
return "The length should be greater than or equal to 8.";
}
return;
}
?>
Screenshot:
Code:
OUTPUT:
Explanation of Code:
Note: For any change in the code or doubt please feel free to comment. Thanks.