Here's a one-liner. You'll get at least one lower-case, one upper-case, one number, and one symbol. Uses random_int
which is supposed to cyrptographically secure. I do not claim this to be secure, though. I am not a security expert.
To copy+Paste: (just change $len
to your desired length.)
$len=26;for ($chars = array('0123456789','abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ','!@#$%^&*()_+-='),$randomString="",$i=0;$i<$len;$i++)$randomString .= substr($chars[$i%4], random_int(0,strlen($chars[$i%4])), 1);
echo $randomString;
And a little more broken down:
for (
$chars = array('0123456789','abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ','!@#$%^&*()_+-='),
$randomString="",
$i=0;
$i<12;$i++)
$randomString .=
substr($chars[$i%4],
random_int(0, strlen($chars[$i%4])), 1);
I use $chars[$i%4]
in the loop to choose which set of characters to get a random from. It guarantees multiple characters from each set of chars in the array.
It could definitely be improved (randomizing how many of each char set there is), but it's good enough for my purposes.