1function generateRandomString($length = 25) {
2 $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
3 $charactersLength = strlen($characters);
4 $randomString = '';
5 for ($i = 0; $i < $length; $i++) {
6 $randomString .= $characters[rand(0, $charactersLength - 1)];
7 }
8 return $randomString;
9}
10//usage
11$myRandomString = generateRandomString(5);
1//generates 13 character random unique alphanumeric id
2echo uniqid();
3//output - 5e6d873a4f597
1function generateRandomString($length = 10) {
2 $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
3 $charactersLength = strlen($characters);
4 $randomString = '';
5 for ($i = 0; $i < $length; $i++) {
6 $randomString .= $characters[rand(0, $charactersLength - 1)];
7 }
8 return $randomString;
9}
10
11Output the random string with the call below:
12
13// Echo the random string.
14// Optionally, you can give it a desired string length.
15echo generateRandomString();
1function rand_str() {
2 $characters = '0123456789-=+{}[]:;@#~.?/>,<|\!"£$%^&*()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
3 $randomstr = '';
4 for ($i = 0; $i < random_int(50, 100); $i++) {
5 $randomstr .= $characters[rand(0, strlen($characters) - 1)];
6 }
7 return $randomstr;
8 }
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
1<?php
2 function RandomString()
3 {
4 $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
5 $randstring = '';
6 for ($i = 0; $i < 10; $i++) {
7 $randstring = $characters[rand(0, strlen($characters))];
8 }
9 return $randstring;
10 }
11
12 RandomString();
13 echo $randstring;