Generate random password in PHP
Snippet
To create a password with the desired character, just build a string of alphabet($alphabet
) with specific chars a-z
, A-Z
, 0-9
(or whatever you want).
<?php
function generatePassword($length = 8) {
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$count = mb_strlen($alphabet);
for ($i = 0, $result = ''; $i < $length; $i++) {
$index = mt_rand(0, $count - 1);
$result .= mb_substr($alphabet, $index, 1);
}
return $result;
}
echo generatePassword(12);
If you are on PHP7 you could use the random_int() function instead of mt_rand
:
<?php
function generatePassword($length = 8) {
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$count = mb_strlen($alphabet);
for ($i = 0, $result = ''; $i < $length; $i++) {
$index = random_int(0, $count - 1);
$result .= mb_substr($alphabet, $index, 1);
}
return $result;
}
echo generatePassword(12);
If you need to generate a strong password you can use our tool - generate password online.