Last active
March 10, 2017 10:21
-
-
Save gskema/c2618438e8604fd17342563340dc5e6f to your computer and use it in GitHub Desktop.
PHP random alphanumeric string generation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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