Created
March 26, 2017 21:36
-
-
Save kaecyra/1b81667a1e3b6ceaa4aa4ee1d18c8c47 to your computer and use it in GitHub Desktop.
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
<?php | |
function randomString($length, $characterOptions = 'A0') { | |
$characterClasses = array( | |
'A' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', | |
'a' => 'abcdefghijklmnopqrstuvwxyz', | |
'0' => '0123456789', | |
'!' => '~!@#$^&*_+-' | |
); | |
if (strlen($characterOptions) > count($characterClasses)) { | |
$characters = $characterOptions; | |
} else { | |
$characterOptionsArray = str_split($characterOptions, 1); | |
$characters = ''; | |
foreach ($characterOptionsArray as $char) { | |
if (array_key_exists($char, $characterClasses)) { | |
$characters .= $characterClasses[$char]; | |
} | |
} | |
} | |
$charLen = strlen($characters); | |
$randomChars = []; | |
$cryptoStrong = false; | |
if (function_exists('openssl_random_pseudo_bytes')) { | |
$randomChars = unpack('C*', openssl_random_pseudo_bytes($length, $cryptoStrong)); | |
} elseif (function_exists('mcrypt_create_iv')) { | |
$randomChars = unpack('C*', mcrypt_create_iv($length)); | |
$cryptoStrong = true; | |
} else { | |
for ($i = 0; $i < $length; $i++) { | |
$randomChars[] = mt_rand(); | |
} | |
} | |
$string = ''; | |
foreach ($randomChars as $c) { | |
$offset = (int)$c % $charLen; | |
$string .= substr($characters, $offset, 1); | |
} | |
return $string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment