- floor: documentation ( source)
- ord: documentation ( source)
<?php
function password($len = 12) {
$ret = '';
$chars = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$strlen = strlen($chars);
$cutoff = floor(256 / $strlen) * $strlen;
for (;;) {
$byte = ord(openssl_random_pseudo_bytes(1)[0]);
if ($byte >= $cutoff) {
continue;
}
echo ($byte % $strlen).PHP_EOL;
$ret .= $chars[$byte % $strlen];
if (strlen($ret) >= $len) {
return $ret;
}
}
}
echo password();