Created
March 16, 2022 01:14
-
-
Save mdestafadilah/791fd5f39e1b84518e2e3b625fecba46 to your computer and use it in GitHub Desktop.
Genereator Random Text (uniq)
This file contains 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
# source: https://gist.github.com/raveren/5555297 | |
if ( !function_exists('random_text')) { | |
function random_text( $type = 'alnum', $length = 8 ) { | |
switch ( $type ) { | |
case 'alnum': | |
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
break; | |
case 'alpha': | |
$pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
break; | |
case 'hexdec': | |
$pool = '0123456789abcdef'; | |
break; | |
case 'numeric': | |
$pool = '0123456789'; | |
break; | |
case 'nozero': | |
$pool = '123456789'; | |
break; | |
case 'distinct': | |
$pool = '2345679ACDEFHJKLMNPRSTUVWXYZ'; | |
break; | |
default: | |
$pool = (string) $type; | |
break; | |
} | |
$crypto_rand_secure = function ( $min, $max ) { | |
$range = $max - $min; | |
if ( $range < 0 ) return $min; // not so random... | |
$log = log( $range, 2 ); | |
$bytes = (int) ( $log / 8 ) + 1; // length in bytes | |
$bits = (int) $log + 1; // length in bits | |
$filter = (int) ( 1 << $bits ) - 1; // set all lower bits to 1 | |
do { | |
$rnd = hexdec( bin2hex( openssl_random_pseudo_bytes( $bytes ) ) ); | |
$rnd = $rnd & $filter; // discard irrelevant bits | |
} while ( $rnd >= $range ); | |
return $min + $rnd; | |
}; | |
$token = ""; | |
$max = strlen( $pool ); | |
for ( $i = 0; $i < $length; $i++ ) { | |
$token .= $pool[$crypto_rand_secure( 0, $max )]; | |
} | |
return $token; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment