Reputation: 186
I'm doing a small program for generating random 4-letters passwords. What I've already achieved is every time I refresh the page, it gives me exactly 4-letters password with exactly uppercase and lowercase letters, and integers using Regex.
The problem I'm trying to solve now is it sometime doesn't give a thing...Ok
I'm asking for solution to how to skip empty values..
$str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$pass=array();
$length=strlen($str)-1;
for($i=0;$i<4;$i++){
$index=rand(0,$length);
$pass[]=$str[$index];
}
$nPass=implode($pass);
echo "Password could be: ";
foreach($pass as $val){
if(preg_match("/[a-z]/",$nPass)&&preg_match("/[A-Z]/",$nPass)&&preg_match("/[0-9]/",$nPass)){
echo $val;
}elseif(empty($nPass)){
echo "NOT FOUND";
}
//echo "null";
}
Please suggest a solution. Thanks in advance.
Upvotes: 1
Views: 89
Reputation: 91430
I'd do:
function gener_pass() {
$lower = str_shuffle('abcdefghijklmnopqrstuvwxyz');
$upper = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
$digit = str_shuffle('0123456789');
$all = str_shuffle($lower . $upper . $digit);
return str_shuffle($lower[0] . $upper[0] . $digit[0] . $all[0]);
}
for($i=0; $i<10; $i++) {
echo gener_pass(),"\n";
}
output:
T8tj
cME4
N5o7
zB24
n3VC
zYE7
b5WK
oRY2
uX5A
PDc8
Upvotes: 1
Reputation: 15141
Hope it will work fine:
$password= generatePassword();
while(!preg_match("/[a-z]/", $password) || !preg_match("/[A-Z]/", $password) || !preg_match("/[0-9]/", $password))
{
$password= generatePassword();
}
echo $password;
function generatePassword()
{
$str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$pass = array();
$length = strlen($str) - 1;
for ($i = 0; $i < 4; $i++)
{
$index = rand(0, $length);
$pass[] = $str[$index];
}
$nPass = implode($pass);
return $nPass;
}
Upvotes: 0