Skip to content

Instantly share code, notes, and snippets.

@rseon
Last active June 18, 2019 08:35
Show Gist options
  • Save rseon/0f15fb09035ba00ae49088645773fc43 to your computer and use it in GitHub Desktop.
Save rseon/0f15fb09035ba00ae49088645773fc43 to your computer and use it in GitHub Desktop.
Random password generator (from Prestashop 1.7.4.3)
<?php
/**
* Random password generator
*
* @param int $length Desired length (optional)
* @param string $flag Output type (NUMERIC, ALPHANUMERIC, NO_NUMERIC, RANDOM)
* @return bool|string Password
*/
function passwdGen($length = 8, $flag = 'ALPHANUMERIC')
{
$length = (int)$length;
if ($length <= 0) {
return false;
}
switch ($flag) {
case 'NUMERIC':
$str = '0123456789';
break;
case 'NO_NUMERIC':
$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'RANDOM':
$num_bytes = ceil($length * 0.75);
$bytes = getBytes($num_bytes);
return substr(rtrim(base64_encode($bytes), '='), 0, $length);
case 'ALPHANUMERIC':
default:
$str = 'abcdefghijkmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
}
$bytes = getBytes($length);
$position = 0;
$result = '';
for ($i = 0; $i < $length; $i++) {
$position = ($position + ord($bytes[$i])) % strlen($str);
$result .= $str[$position];
}
return $result;
}
/**
* Random bytes generator
* Limited to OpenSSL since 1.7.0.0
*
* @param int $length Desired length of random bytes
* @return bool|string Random bytes
*/
function getBytes($length)
{
$length = (int) $length;
if ($length <= 0) {
return false;
}
$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);
if ($cryptoStrong === true) {
return $bytes;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment