PHP7: Generate secure password based on a string of allowed characters

There are quite some easy implementations out there to generate a secure random string in PHP, most of them by encoding a binary string using Base64 or bin2hex. However, this limits the characters used in your password (Base64 = A-Z, a-z, 0-9 and + and /; bin2hex = 0-9 and a-f).

 

Here I’ll share my solution to generate a secure password (requires PHP 7) based on a predefined character string. This leaves you the option to add complex characters (*/-+%{}&@# etc) or leave out similarly readable ones (O and 0, I and l,…).

$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789*/-+[]{}&#';
$pass = '';
for ($x=0; $x<24; $x++) {
  $pass .= $chars[hexdec(bin2hex(random_bytes(1)))%strlen($chars)];
}

You can modify the length of your password by changing the 24 into anything desired, and adding or removing characters from the $chars string.