Skip to content

Instantly share code, notes, and snippets.

@dingo-d
Last active April 12, 2019 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dingo-d/b93eacb2c7d9dd7587c60174bf707e7f to your computer and use it in GitHub Desktop.
Save dingo-d/b93eacb2c7d9dd7587c60174bf707e7f to your computer and use it in GitHub Desktop.
Random string generator
<?php
/**
* The random string generator helper
*
* Solution implemented from http://stackoverflow.com/a/13733588/1056679
*
* Usage: CLI: php random.php {length}
* length - length of the random string to generage
*
* @since 1.0.0
* @package Randomness
*/
namespace Randomness;
/**
* Class Random Generator
*
* Generates random alphanumeric characters.
*/
class Random_Generator {
/**
* Generate random string of specified length
*
* @param int $length Length of the string.
* @return string Radnom string.
*/
public function generate( int $length ) : string {
$token = '';
$length = abs( $length );
for ( $i = 0; $i < $length; $i++ ) {
$random_key = $this->get_random_integer( 0, $this->get_alphabet_length() );
$token .= $this->get_alphabet()[ $random_key ];
}
return $token;
}
/**
* Get the default alphabet
*
* @return string String of all the allowed characters.
*/
private function get_alphabet() : string {
return implode( range( 'a', 'z' ) )
. implode( range( 'A', 'Z' ) )
. implode( range( 0, 9 ) );
}
/**
* Get length of the default alphabet
*
* @return int The length of the alphabet.
*/
private function get_alphabet_length() : int {
return strlen( $this->get_alphabet() );
}
/**
* Get random integer in the given range
*
* @param int $min Min value for the random integer range.
* @param int $max Max value for the random integer range.
* @return int Random integer
*/
private function get_random_integer( int $min, int $max ) : int {
$range = ( $max - $min );
$log = log( $range, 2 );
// Length in bytes.
$bytes = (int) ( $log / 8 ) + 1;
// Length in bits.
$bits = (int) $log + 1;
// Set all lower bits to 1.
$filter = (int) ( 1 << $bits ) - 1;
do {
$rnd = hexdec( bin2hex( openssl_random_pseudo_bytes( $bytes ) ) );
$rnd = $rnd & $filter;
} while ( $rnd >= $range );
return ( $min + $rnd );
}
}
$random = new Random_Generator();
if (php_sapi_name() == "cli") {
echo $random->generate( $argv[1] ), "\n";
} else {
echo $random->generate( $_GET['len'] );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment