Generate (pseudo) random alphanumeric strings

How can I generate a (pseudo) random alphanumeric string, for example: "d79jd8c" in PHP?

+80
php random
Sep 07 '08 at 4:02
source share
18 answers

First create a line with all your possible characters:

$characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; 

You can also use range () to make it faster.

Then, in a loop, select a random number and use it as an index for the string $characters to get a random character and add it to the string:

  $string = ''; $max = strlen($characters) - 1; for ($i = 0; $i < $random_string_length; $i++) { $string .= $characters[mt_rand(0, $max)]; } 

$random_string_length - the length of a random string.

+158
Sep 07 '08 at 4:06
source share

I like this feature for assignment

 function randomKey($length) { $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z')); for($i=0; $i < $length; $i++) { $key .= $pool[mt_rand(0, count($pool) - 1)]; } return $key; } echo randomKey(20); 
+18
Nov 28 '15 at 13:37
source share

Generate a cryptographically strong , random (potentially) 8-character string using the openssl_random_pseudo_bytes function:

 echo bin2hex(openssl_random_pseudo_bytes(4)); 

Procedural method:

 function randomString(int $length): string { return bin2hex(openssl_random_pseudo_bytes($length)); } 

Update:

PHP7 introduced random_x() functions that should be even better. If you came from PHP 5.X, use the excellent paragonie / random_compat library, which is the polyfill for random_bytes () and random_int () from PHP 7.

 function randomString($length) { return bin2hex(random_bytes($length)); } 
+13
Feb 24 '16 at
source share

Single line solution:

 echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 ); 

You can change the substr parameter to specify a different length for your string.

+6
Aug 08 '17 at 19:55 on
source share

Use the ASCII table to select a range of letters, where: $ range_start, $ range_end is the value from the decimal column to the ASCII table.

I find that this method compares better with the described method , where a range of characters is defined within a specific string.

 // range is numbers (48) through capital and lower case letters (122) $range_start = 48; $range_end = 122; $random_string = ""; $random_string_length = 10; for ($i = 0; $i < $random_string_length; $i++) { $ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range // finds the character represented by $ascii_no and adds it to the random string // study **chr** function for a better understanding $random_string .= chr( $ascii_no ); } echo $random_string; 

More details:

+4
07 Sep '08 at 10:04
source share

I know this old post, but I would like to contribute to the class that I created based on Jeremy Ruthen's answer, and improved with the suggestions in the comments:

  class RandomString { private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; private static $string; private static $length = 8; //default random string length public static function generate($length = null) { if($length){ self::$length = $length; } $characters_length = strlen(self::$characters) - 1; for ($i = 0; $i < self::$length; $i++) { self::$string .= self::$characters[mt_rand(0, $characters_length)]; } return self::$string; } } 
+4
Nov 13 '15 at 10:38
source share

Maybe I missed something here, but here, using the uniqid () function .

+2
Jun 26 '10 at 23:40
source share

I made the following quick function to play with the range() function. It may someday help someone.

 Function pseudostring($length = 50) { // Generate arrays with characters and numbers $lowerAlpha = range('a', 'z'); $upperAlpha = range('A', 'Z'); $numeric = range('0', '9'); // Merge the arrays $workArray = array_merge($numeric, array_merge($lowerAlpha, $upperAlpha)); $returnString = ""; // Add random characters from the created array to a string for ($i = 0; $i < $length; $i++) { $character = $workArray[rand(0, 61)]; $returnString .= $character; } return $returnString; } 
+2
Apr 29 '16 at 7:52
source share

You can use the following code copied from in this article . It is similar to existing functions, except that you can force a special character:

 function random_string() { // 8 characters: 7 lower-case alphabets and 1 digit $character_set_array = array(); $character_set_array[] = array('count' => 7, 'characters' => 'abcdefghijklmnopqrstuvwxyz'); $character_set_array[] = array('count' => 1, 'characters' => '0123456789'); $temp_array = array(); foreach ($character_set_array as $character_set) { for ($i = 0; $i < $character_set['count']; $i++) { $temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)]; } } shuffle($temp_array); return implode('', $temp_array); } 
+1
Jun 24 '09 at 8:42
source share
 function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } echo generateRandomString(); 
+1
Mar 08 '15 at 10:48
source share

If you want a very simple way to do this, you can rely on existing PHP functions. This is the code I'm using:

substr( sha1( time()), 0, 15 )

time() gives you the current time in seconds since the beginning of the era, sha1() encrypts it in the string 0-9a-f, and substr() allows you to choose the length. You do not need to start with the character 0, and no matter what the difference between the two numbers is, the length of the string.

+1
Apr 16 '18 at 14:51
source share

Simple guys .... but remember that each byte is random between 0 and 255, which would be good for a random string. Also remember that you will have two characters to represent each byte.

 $str = bin2hex(random_bytes(32)); // 64 character string returned 
+1
May 02 '19 at 2:59
source share

Jeremy's answer is great. If, like me, you do not know how to implement range (), you can see my version with range ().

 <?php $character_array = array_merge(range('a', 'z'), range(0, 9)); $string = ""; for($i = 0; $i < 6; $i++) { $string .= $character_array[rand(0, (count($character_array) - 1))]; } echo $string; ?> 

This does the same as Jeremy, but uses concatenated arrays where he uses a string, and uses count (), where he uses strlen ().

0
Jun 22 '10 at 18:37
source share

This is what I use:

 $cryptoStrong = true; // can be false $length = 16; // Any length you want $bytes = openssl_random_pseudo_bytes($length, $cryptoStrong); $randomString = bin2hex($bytes); 

Here you can see Docs for openssl_random_pseudo_bytes , and Docs for bin2hex here

0
Dec 28 '16 at 11:44
source share

1 line:

 $FROM = 0; $TO = 'zzzz'; $code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36); echo $code; 
0
May 11 '17 at 15:19
source share

A modern way to do this with the hint type / rand_int for real randomness

 function random_string(int $size): string { $characters = array_merge( range(0, 9), range('A', 'Z') ); $string = ''; $max = count($characters) - 1; for ($i = 0; $i < $size; $i++) { $string .= $characters[random_int(0, $max)]; } return $string; } 
0
Nov 05 '18 at 15:15
source share

List the characters you need first

 $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 

Use the str_shuffle ($ string) function. This function will provide you with a randomly mixed string.

 $alpha=substr(str_shuffle($chars), 0, 50); 

50 is the length of the string.

0
May 11 '19 at 11:42
source share
 public function randomString($length = 8) { $characters = implode([ 'ABCDEFGHIJKLMNOPORRQSTUWVXYZ', 'abcdefghijklmnoprqstuwvxyz', '0123456789', //'!@#$%^&*?' ]); $charactersLength = strlen($characters) - 1; $string = ''; while ($length) { $string .= $characters[mt_rand(0, $charactersLength)]; --$length; } return $string; } 
0
May 11 '19 at 11:48
source share



All Articles