Skip to content

Instantly share code, notes, and snippets.

@gskema
Last active March 10, 2017 10:21
Show Gist options
  • Save gskema/c2618438e8604fd17342563340dc5e6f to your computer and use it in GitHub Desktop.
Save gskema/c2618438e8604fd17342563340dc5e6f to your computer and use it in GitHub Desktop.
PHP random alphanumeric string generation
<?php
class RandomStringGenerator
{
const DEFAULT_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789';
/**
* Generates a random string of requested length and from given alphabet.
*
* @param int $stringLength
* @param string $alphabet
*
* @return string
*/
public function generate(int $stringLength, string $alphabet = self::DEFAULT_ALPHABET)
{
$len = strlen($alphabet);
if ($stringLength > $len) {
$multiplier = (int)ceil($stringLength / $len);
$alphabet = str_repeat($alphabet, $multiplier);
}
return substr(str_shuffle($alphabet), 0, $len);
}
/**
* Smaller alpabet, but more cryptographically random [a-f0-9] (hexadecimal)
*/
function generate1($stringLength)
{
return mb_substr(bin2hex(random_bytes($stringLength)), 0, $stringLength);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment