Skip to content

Instantly share code, notes, and snippets.

@anxp
Created February 21, 2019 19:52
Show Gist options
  • Save anxp/153a8bf47773f2b43e4002a02574c997 to your computer and use it in GitHub Desktop.
Save anxp/153a8bf47773f2b43e4002a02574c997 to your computer and use it in GitHub Desktop.
PHP Random String Generator
<?php
/**
* Generate a random string, using a cryptographically secure
* pseudorandom number generator (random_int)
*
* For PHP 7, random_int is a PHP core function
* For PHP 5.x, depends on https://github.com/paragonie/random_compat
*
* @param int $length How many characters do we want?
* @param string $keyspace A string of all possible characters
* to select from
* @return bool|string
*/
function randString(int $length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
$pieces = [];
$max = mb_strlen($keyspace, '8bit') - 1;
try {
for ($i = 0; $i < $length; ++$i) {
$pieces [] = $keyspace[random_int(0, $max)];
}
} catch (Exception $e) {
return FALSE;
}
return implode('', $pieces);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment