Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Tools {
- /**
- * Generates a random string of a variable length and charset
- * @param int $length
- * Length of the returned string
- * @param string $chars
- * Charset
- * @return string
- * Random string of the set length using the set charset
- */
- public static function GenerateRandomString($length = 10, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') {
- $cCount = strlen($chars);
- $r = '';
- for ($i = 0; $i < $length; $i++) {
- $r .= $chars[rand(0, $cCount - 1)];
- }
- return $r;
- }
- /**
- * Generates an array of random strings (no doubles) with a variable count, length and charset
- * @param $count
- * Amount of entries in the returned array
- * @param $length
- * Length of the returned strings
- * @param string $chars
- * Charset
- * @return array|bool
- * Array on success - False on failure (requested a higher count than possible with the set charset and string length)
- */
- public static function GenerateRandomStringArray($count, $length, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') {
- if(pow(strlen($chars), $length) >= $count){
- $arr = array();
- $i = 0;
- while($i < $count) {
- $str = Tools::GenerateRandomString($length, $chars);
- if(!in_array($str, $arr)) {
- $arr[] = $str;
- $i++;
- }
- }
- return $arr;
- }
- else return false;
- }
- }
- ?>
- Tools::GenerateRandomStringArray(10, 16) =>
- array(10) {
- [0]=> string(16) "eCegsdzjJqhjxky9"
- [1]=> string(16) "Qv9686e3lCykXekM"
- [2]=> string(16) "WvgLLwB7pU3akJOM"
- [3]=> string(16) "vAChnzHwXhKRGO18"
- [4]=> string(16) "wLcDXdvhXLGoZvWN"
- [5]=> string(16) "23YQwr3orkPLhMzO"
- [6]=> string(16) "ZoZT3giPoZcZxEWb"
- [7]=> string(16) "qRdMwGgCOKM4K81T"
- [8]=> string(16) "jpEwYHWLHBAXWbOX"
- [9]=> string(16) "G4k7pjle4xCH7Pkm"
- }
- Tools::GenerateRandomStringArray(10, 16, "01") =>
- array(10) {
- [0]=> string(16) "0001001010011111"
- [1]=> string(16) "0001110100010100"
- [2]=> string(16) "0000110011001110"
- [3]=> string(16) "0100010100100011"
- [4]=> string(16) "0001110010010101"
- [5]=> string(16) "1001000111011110"
- [6]=> string(16) "1000111000111110"
- [7]=> string(16) "0111110010111100"
- [8]=> string(16) "1100010100100010"
- [9]=> string(16) "1100000011010001"
- }
Add Comment
Please, Sign In to add comment