Generate a random, unique, alpha-numeric string using PHP.
APPROACH 1: Brute Force
The first approach is the simplest one to understand and thus brute force.
It can be achieved as follows:
- Store all the possible letters into a string.
- Generate random index from 0 to string length-1.
- Print the letter at that index.
- Perform this step n times (where n is the length of string required).
APPROACH 2: Using Hashing Functions
PHP has a few functions like md5(), sha1() and hash(), that can be used to hash a string based on certain algorithms like “sha1”, “sha256”, “md5” etc. All these function takes a string as an argument and output an Alpha-Numeric hashed string.
To learn more about these functions click here.
Once we understand how we utilize these functions, our task becomes pretty simple.
- Generate a random number using rand() function.
- Hash it using one of the above functions.
NOTE: All the above functions are hashing functions, hence the length of the string generated will always depend on the algorithm used, but for an algorithm it will always remain constant. So if you want to generate string of a fixed length, you can either truncate the generated string or concatenate with another string, based on the requirement.
Approach 3:Using uniqid() function.
The uniqid( ) function in PHP is an inbuilt function which is used to generate a unique ID based on the current time in microseconds (micro time). By default, it returns a 13 character long unique string.
NOTE: All the above approaches are built on rand() and uniqid() functions. These functions are not cryptographically secure random generators. So it is advised that if the degree of randomness affect the security of an application, these methods should be avoided.
Approach 4: Using random_bytes() function. (Cryptographically Secure)
The random_bytes() function generates cryptographically secure pseudo-random bytes, which can later be converted to hexadecimal format using bin2hex() function.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.