Change language

Generating a random string using PHP

EA070 aBX32gTf
APPROACH 1: Brute force
First approach - the easiest to understand and therefore brute force. 
This can be achieved like this:
  • Save all possible letters to a string.
  • Generate a random index from 0 to string-1 length.
  • Type a letter in this index.
  • Repeat this step n times (where n - is the required line length).
Program: $n = 10; function getName ( $n ) { $characters = ’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’ ; $randomString = ’’ ; for ( $i = 0; $i < $n ; $i ++) { $index = rand (0, strlen ( $characters ) - 1); $randomString . = $characters [ $index ]; } return $randomString ; } echo getName ( $n ); ?> Output 1:
Output 2:
APPROACH 2. Using hashing functions
PHP has several functions like md5(), sha1() and hash() which can be used to hash a string based on certain algorithms like "sha1", "sha256", "md5", etc. All these functions take a string as an argument and print an alphanumeric hashed string.To learn more about these functions, click here. Once we understand how we use these functions, our task becomes quite simple.
  • Generating a random number using the rand() function.
  • Hash it using one of the above functions.
Program 1: $str = rand ( ); $result = md5 ( $str ); echo $result ; ?> Output 1:
Output 2:
Program 2: $str = rand() ; $result = sha1 ( $str ); echo $result ; ?> Output 1:
Output 2:
Program 3: $str = rand(); $result = hash ( "sha256 " , $str ); echo $result ; ?> Output 1:
2a41cbc8cc11f8c8d0eb54210fe524748b4def1c5b04fcf18c2d5972e24d11c2 / pre> Output 2:
NOTE.All of the above functions are hash functions, so the length of the generated string will always be used algorithm, but for the algorithm it will always remain constant. So if you want to generate a fixed-length string, you can either truncate the generated string or concatenate it with another string, depending on your requirements.Approach 3: Using the uniqid() function.
Function uniqid() in PHP - it is a built-in function that is used to generate a unique identifier based on the current time in microseconds (micro time). By default, it returns a unique string 13 characters long.Program: $result = uniqid(); echo $result ; ?> Output1:
NOTE.All of the above approaches are based on the rand() and uniqid ( ). These functions are not cryptographically secure random generators. Therefore, it is recommended that these methods should be avoided if the degree of randomness affects the security of the application.Approach 4: Using the random_bytes() function. (Cryptographically secure)
The random_bytes() function generates cryptographically secure pseudo-random bytes that can later be converted to hexadecimal format using bin2hex() .Program: $n = 20; $result = bin2hex (random_bytes ( $n )); echo $result ; ?> Output1: