For passwords, reset tokens and other values that must be hard to guess, choose characters with random_int() or encode random_bytes(). The older rand()-based generator below is retained only as a non-security legacy example.
$alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$result = '';
for ($i = 0; $i < 12; $i++) {
$result .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
echo $result;random_int() so the generated characters are selected with a cryptographically secure random integer source.
<?Php
function random_generator($digits){
$alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ23456789";
$random_generator = "";
for($i=0; $i<$digits; $i++){
$random_generator .= $alphabet[random_int(0, strlen($alphabet)-1)];
}
return $random_generator;
}
echo random_generator(10);
?>
STRING REFERENCE
how to change all the letters to upper case
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| arman patel | 26-05-2009 |
| very comprencive and use full tutorial for me thx. | |
| Harry | 29-07-2009 |
| WOW thanks for this! | |
| bright-tutorials.com | 31-12-2009 |
| This is another method to do it, but there are others. Good job using mt_rand not many use it! | |
| ketan | 08-03-2010 |
| good code for beginner | |
| sattar | 02-10-2012 |
| easy and simple tutor. are available here | |
| Php Programmer | 10-08-2017 |
| Great!! This tutorial was really helpful to create a random number and alphabets. Simple but effective. Thanks. | |