Generate Random Alphanumeric String with PHP
In this article, we will explain how to Generate Random Alphanumeric String with PHP. This is a simple function that allows you to generate random strings containing Letters and Numbers (alphanumeric) using PHP. The random strings can be used for various purposes, including:
Referral Code
Promotional Code
Coupon Code
OTP Code
Generate Random Alphanumeric String with PHP
Now you can see base on above PHP function we created a random_code() function to generate random alphanumeric string.
function random_code($limit) { return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit); } echo random_code(8); //Here's the output samples mocpkwbn 460djcsn j1m10z0t 4kj9cy68
The above script code relies on following PHP functions:
1. PHP base_convert() Function
The base_convert() function is used to convert a number from one base to another.
Example #1 base_convert() example
<?php $hexa = 'D174'; echo base_convert($hexa, 18, 8); ?>
Output:
224756
2. PHP sha1() Function
The PHP sha1() function is used to calculate the sha1 hash of a string.
Example #1 sha1() Function
<?php $str = "Random"; echo sha1($str); ?>
Output:
58d888c08aa561f370e38cee976121532a883d71
3. PHP uniqid() Function
The PHP uniqid function Generate a unique ID.
Example #1 uniqid() Function
<?php echo uniqid(); ?>
Output:
//Here's the uniqid() Function output samples 5b6af218a8eb6 5b6af22304783 5b6af22c4e386 5b6af23fb6bed
4. PHP mt_rand() Function
The PHP mt_rand() function generates a random integer using the Mersenne Twister algorithm.
Example #1 mt_rand() Function
<?php echo mt_rand(); ?>
Output:
//Here's the mt_rand() Function output samples 576535237 1894593969 1647369290 1903411751
Live Demo
I hope you like this Post, Please send me any comment, suggestion or correction you may have – we are here to solve your problems. Thanks
Hello,
Is there likely to repeat the output given by this code?
yes right there is change repeat the output, for it you can store code in database and recheck it before store new code in database .
hi how about coding for random football team generator
hi how about coding for random football team generator
None of these methods are cryptographically secure. Use bin2hex(random_bytes(5)) or something instead.