Generate a random string

@param int  $length String length
@param bool $raw    Return RAW data instead of ascii

@return string The generated random string
772823
public static function random_bytes($length, $raw = false)
    {
        $hextab  = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $tabsize = strlen($hextab);

        // Use PHP7 true random generator
        if ($raw && function_exists('random_bytes')) {
            return random_bytes($length);
        }

        if (!$raw && function_exists('random_int')) {
            $result = '';
            while ($length-- > 0) {
                $result .= $hextab[random_int(0, $tabsize - 1)];
            }

            return $result;
        }

        $random = openssl_random_pseudo_bytes($length);

        if ($random === false && $length > 0) {
            throw new Exception("Failed to get random bytes");
        }

        if (!$raw) {
            for ($x = 0; $x < $length; $x++) {
                $random[$x] = $hextab[ord($random[$x]) % $tabsize];
            }
        }

        return $random;
    }
360813
public static function generator( $length = 32 ) {
		$out = Hash::base64( Route::HTTP_HOST() . random_bytes( $length ), 1 );

		return $out;
	}
604866
public function generateRandomString(int $length = 32): string
    {
        if ($length < 1) {
            throw new \RuntimeException('First parameter ($length) must be greater than 0');
        }

        $bytes = $this->generateRandomKey($length);
        return \substr(StringHelper::base64UrlEncode($bytes), 0, $length);
    }
1195689
public static function generate($length = 10, $charlist = '0-9a-z')
	{
		$charlist = str_shuffle(preg_replace_callback('#.-.#', function($m) {
			return implode('', range($m[0][0], $m[0][2]));
		}, $charlist));
		$chLen = strlen($charlist);

		static $rand3;
		if (!$rand3) {
			$rand3 = md5(serialize($_SERVER), TRUE);
		}

		$s = '';
		for ($i = 0; $i < $length; $i++) {
			if ($i % 5 === 0) {
				list($rand, $rand2) = explode(' ', microtime());
				$rand += lcg_value();
			}
			$rand *= $chLen;
			$s .= $charlist[($rand + $rand2 + ord($rand3[$i % strlen($rand3)])) % $chLen];
			$rand -= (int) $rand;
		}
		return $s;
	}
887369
public static function randAlphabetAndNumbers($length)
    {
        if ($length < 0) $length = 1;
        if ($length > 64) $length = 64;
        $code = [];
        for ($i = 0; $i < $length; $i++) {
            $code[$i] = self::$codeSet[mt_rand(0, strlen(self::$codeSet) - 1)];
        }
        return implode("", $code);
    }
117537
public function generateHardReadableString($length)
    {
        return $this->generateRandomString($length, self::SYMBOLS . self::CHARS . self::NUMBERS . self::SYMBOLS);
    }
599538
private static function generateRandomString($length = 10)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $string = '';

        for ($i = 0; $i < $length; $i++) {
            $string .= $characters[rand(0, strlen($characters) - 1)];
        }

        return $string;
    }
728272
private function random(int $length = 32): string
    {
        try {
            if (empty($string = random_bytes($length))) {
                throw new \RuntimeException("Unable to generate random string");
            }
        } catch (\Throwable $e) {
            throw new \RuntimeException("Unable to generate random string", $e->getCode(), $e);
        }

        return substr(base64_encode($string), 0, $length);
    }
375011
public static function randAlphabet($length)
    {
        if ($length < 0) $length = 1;
        if ($length > 64) $length = 64;
        $code = [];
        for ($i = 0; $i < $length; $i++) {
            $code[$i] = self::$alphaCodeSet[mt_rand(0, strlen(self::$alphaCodeSet) - 1)];
        }
        return implode("", $code);
    }
504351
public static function string(
        int $length = 32,
        string $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    ) : string {
        $rand = static::bytes($length * 2);
        $lngt = iconv_strlen($characters, 'UTF-8');
        $rslt = '';
        for ($i = 0; $i < strlen($rand); ++$i) {
            $rslt .= iconv_substr($characters, ord($rand[$i]) % $lngt, 1, 'UTF-8');
        }
        return iconv_substr($rslt, 0, $length, 'UTF-8');
    }
653185
protected function generateNonce( $length = 32 )
    {
        $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $result = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            $result .= $chars[mt_rand( 0, strlen( $chars ) - 1 )];
        }

        return $result;
    }
1078518
static function getRandomString($length = 8)
    {

        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

        $value = '';
        $charsLength = strlen($chars) - 1;

        for ($i = 1 ; $i <= $length; $i++) {
            $value .= $chars[rand(0, $charsLength)];
        }

        return $value;

    }
301789
static function get_random_str($length = 16)
    {
        $str = "";
        $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($str_pol) - 1;
        for ($i = 0; $i < $length; $i++) {
            $str .= $str_pol[mt_rand(0, $max)];
        }
        return $str;
    }
143195
public static function randomLatinNumeric(int $length): string
    {
        $ret = 97;
        $out = null;
        for ($i = 0; $i < $length; $i++) {
            $offset = mt_rand(0, 15);
            $char = chr($ret + $offset);
            $posibility = mt_rand(0, 2);
            if ($posibility == 0) {
                // 33% - add random numeric
                $out .= mt_rand(0, 9);
            } elseif ($posibility == 1) {
                // 33% - make upper offset+ret
                $out .= strtoupper($char);
            } else {
                $out .= $char;
            }
        }
        return $out;
    }
697481
public static function generate($length = 32, $charset = 'abcdefghijklmnopqrstuvwxyz')
    {
        // Type checks:
        if (!is_numeric($length)) {
            throw new \InvalidArgumentException(
                'random_str - Argument 1 - expected an integer'
            );
        }
        if (!is_string($charset)) {
            throw new \InvalidArgumentException(
                'random_str - Argument 2 - expected a string'
            );
        }

        if ($length < 1) {
            // Just return an empty string. Any value < 1 is meaningless.
            return '';
        }

        // Remove duplicate characters from $charset
        $split = str_split($charset);
        $charset = implode('', array_unique($split));

        // This is the maximum index for all of the characters in the string $charset
        $charset_max = strlen($charset) - 1;
        if ($charset_max < 1) {
            // Avoid letting users do: random_str($int, 'a'); -> 'aaaaa...'
            throw new \LogicException(
                'random_str - Argument 2 - expected a string that contains at least 2 distinct characters'
            );
        }
        // Now that we have good data, this is the meat of our function:
        $random_str = '';
        for ($i = 0; $i < $length; ++$i) {
            $r = random_int(0, $charset_max);
            $random_str .= $charset[$r];
        }

        return $random_str;
    }
924413
public static function generateNonce($length = 30)
    {
        $random = null;
        if ($length < 1) {
            throw new Exception('$length must be greater than 0');
        }

        // Use the new PHP 7 random_bytes call, if available
        if (!$random && function_exists('random_bytes')) {
            $random = random_bytes($length);
        }

        // Get some random binary data from open ssl, if available
        if (!$random && function_exists('openssl_random_pseudo_bytes')) {
            $random = openssl_random_pseudo_bytes($length);
        }

        // Fallback to /dev/urandom
        if (!$random && is_readable('/dev/urandom')) {
            if (($handle = @fopen('/dev/urandom', 'rb')) !== false) {
                $random = @fread($handle, $length);
                @fclose($handle);
            }
        }

        // Fallback if no random bytes were found
        if (!$random) {
            $random = microtime();

            for ($i = 0; $i < 1000; $i += $length) {
                $random = sha1(microtime() . $random);
            }
        }

        // Convert to base64
        $random = base64_encode($random);

        // Replace unsafe chars
        $random = strtr($random, '+/', '-_');
        $random = str_replace('=', '', $random);

        // Truncate the string to specified lengh
        $random = substr($random, 0, $length);

        return $random;
    }
1069751
public static function random($length = 64, $characters = self::ALNUM)
    {
        static $random_generator = null;

        if (null === $random_generator) {
            $random_generator = is_callable('mt_rand') ? 'mt_rand' : 'rand';
        }

        $len = strlen($characters);
        return join(
            '',
            array_map(
                function () use ($characters, $len, $random_generator) {
                    return $characters{$random_generator(0, $len - 1)};
                },
                range(0, $length - 1)
            )
        );
    }