1/**
2 * Generate a random string, using a cryptographically secure
3 * pseudorandom number generator (random_int)
4 *
5 * This function uses type hints now (PHP 7+ only), but it was originally
6 * written for PHP 5 as well.
7 *
8 * For PHP 7, random_int is a PHP core function
9 * For PHP 5.x, depends on https://github.com/paragonie/random_compat
10 *
11 * @param int $length How many characters do we want?
12 * @param string $keyspace A string of all possible characters
13 * to select from
14 * @return string
15 */
16function random_str(
17 int $length = 64,
18 string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
19): string {
20 if ($length < 1) {
21 throw new \RangeException("Length must be a positive integer");
22 }
23 $pieces = [];
24 $max = mb_strlen($keyspace, '8bit') - 1;
25 for ($i = 0; $i < $length; ++$i) {
26 $pieces []= $keyspace[random_int(0, $max)];
27 }
28 return implode('', $pieces);
29}
30
1phpCopy<?php
2$Random_str = uniqid();
3echo "Random String:", $Random_str, "\n";
4?>
5
1phpCopy<?php
2
3echo "Out1: ",substr(md5(time()), 0, 16),"\n";
4
5echo "Out2: ",substr(sha1(time()), 0, 16),"\n";
6
7echo "Out3: ",md5(time()),"\n";
8
9echo "Out4: ",sha1(time()),"\n";
10
11?>
12
1phpCopy<?php
2 $x = 0;
3 $y = 10;
4$Strings = '0123456789abcdefghijklmnopqrstuvwxyz';
5echo "Gen_rand_str: ",substr(str_shuffle($Strings), $x, $y), "\n";
6
7$a = 0;
8$b = 20;
9$Strings='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
10echo "Gen_My_Pass: ",'hello.'.substr(str_shuffle($Strings), $a, $b).'.World',"\n";
11?>
12
1phpCopy<?php
2
3function secure_random_string($length) {
4 $rand_string = '';
5 for($i = 0; $i < $length; $i++) {
6 $number = random_int(0, 36);
7 $character = base_convert($number, 10, 36);
8 $rand_string .= $character;
9 }
10
11 return $rand_string;
12}
13
14echo "Sec_Out_1: ",secure_random_string(10),"\n";
15
16echo "Sec_Out_2: ",secure_random_string(10),"\n";
17
18echo "Sec_Out_3: ",secure_random_string(10),"\n";
19
20?>
21
1phpCopy<?php
2
3echo "Output-1: ",bin2hex(random_bytes(10)),"\n";
4
5echo "Output-2: ",bin2hex(random_bytes(20)),"\n";
6
7echo "Output-3: ",bin2hex(random_bytes(24)),"\n";
8
9?>
10
1phpCopy<?php
2function random_str_generator ($len_of_gen_str){
3 $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
4 $var_size = strlen($chars);
5 echo "Random string =";
6 for( $x = 0; $x < $len_of_gen_str; $x++ ) {
7 $random_str= $chars[ rand( 0, $var_size - 1 ) ];
8 echo $random_str;
9 }
10echo "\n";
11}
12random_str_generator (8)
13?>
14