i know this might seem silly, but i want to generate a random code of 8 characetrs, only numbers or letters using php. i needs this to generate a password for each user that signs up, thanks
8 Answers
I would rather use md5 to generate passwords
But you can use something like this if you want a custom:
function createRandomPassword() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}

- 3,482
- 3
- 31
- 50
-
1using the `md5()` idea, you could take the `$pass` your are returning now and instead do `return substr(md5($pass), 0, 8);` – Patrick Dec 31 '10 at 16:05
-
i presume the L and 1 are left on purpose! because they look alike? – Nijboer IT Mar 20 '14 at 10:57
-
The advantage of this over md5 or some other hash function is that you can leave out characters that look similar, such as the above example leaves out L and 1. – Tim Dearborn Jan 07 '15 at 04:11
-
I'd now use something like this: ``` $chars = "abcdefghijkmnopqrstuvwxyz023456789"; $i = 0; $token = ''; while ($i <= 7) { $num = \random_int(0, 33); $token .= $chars{$num}; $i++; } ``` (uses CSPRNG/pure randomness PHP functions) – jens1o Mar 18 '20 at 16:35
What about something like this, for ease:
$pass = substr(md5(uniqid(mt_rand(), true)) , 0, 8);

- 2,651
- 1
- 21
- 28
A good or efficient method for doing this is:
public function generateRandomString($length = 8) {
$characters = '0123456789abcdefghijklmnopqrs092u3tuvwxyzaskdhfhf9882323ABCDEFGHIJKLMNksadf9044OPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
By changing $length variable you can generate alphanumeric code according to your need.

- 318
- 1
- 10
<?php
$uniqid = uniqid();
$rand_start = rand(1,5);
$rand_8_char = substr($uniqid,$rand_start,8);
?>

- 61,812
- 21
- 118
- 158
-
you might want to salt the time otherwise a hacker might be able to take advantage. it's a long shot, but still possible. – Patrick Dec 31 '10 at 16:08
-
-
-
fine! did not do what you told me to do on principal, BUT I made the starting position for the substring random. better? ;) – jondavidjohn Dec 31 '10 at 16:30
-
i just did a little research and it appears this whole back-and-forth was for naught, you can just add true to the second parameter of `uniqid()` and it will add entropy for unique values :-) – Patrick Dec 31 '10 at 16:41
-
I thought that adds special characters? which he did not want in the password. – jondavidjohn Dec 31 '10 at 16:44
This work like charm and you can choose the type of characters that will be generated like:
"upper_case", "lower_case", "number", "special_character"
function create_random_code($length = 8, $in_params = [])
{
$in_params['upper_case'] = isset($in_params['upper_case']) ? $in_params['upper_case'] : true;
$in_params['lower_case'] = isset($in_params['lower_case']) ? $in_params['lower_case'] : true;
$in_params['number'] = isset($in_params['number']) ? $in_params['number'] : true;
$in_params['special_character'] = isset($in_params['special_character']) ? $in_params['special_character'] : false;
$chars = '';
if ($in_params['lower_case']) {
$chars .= "abcdefghijklmnopqrstuvwxyz";
}
if ($in_params['upper_case']) {
$chars .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
if ($in_params['number']) {
$chars .= "0123456789";
}
if ($in_params['special_character']) {
$chars .= "!@#$%^&*()_-=+;:,.";
}
return substr(str_shuffle($chars), 0, $length);
}
To use it:
echo create_random_code(
6,
[
'upper_case' => true,
'lower_case' => true,
'number' => true,
'special_character' => false
]
);

- 2,070
- 23
- 20
Use base64_encode()
, feed it some rand()
numbers, and cut off the first 8 characters, which are definitely letters or numbers. That's not a totally random combination due to the input being just integers. But it's good enough for default user-passwords. (Else use rand()
via chr()
before encoding.)

- 144,265
- 20
- 237
- 291
PHP has a rand
function (and also a mt_rand
function that the docs claim is faster.)
So do something like this:
$i = 0;
$pwd = "";
while ( $i < 10) {
if (mt_rand() % 2 == 0) {
$pwd .= rand();
} else {
$pwd .= char(rand());
// http://php.net/manual/en/function.chr.php
}
$i += 1;
}

- 155,703
- 32
- 311
- 293
-
another option would be to use `rand()` only once by setting the min & max number allowed ie- `$pwd = rand(10000000, 99999999);` – Patrick Dec 31 '10 at 16:03
-
@Patrick -- good thought! If speed is a problem then you can replace the interior random calls with string concatenation alone or a call to char. – Sean Vieira Dec 31 '10 at 16:10
For your purposes, you can use the following to generate random codes:
bin2hex(random_bytes(10))
Note that here we use random_bytes
, which was introduced in PHP 7 and uses a cryptographic random generator, something that is important if you want random codes to be hard to guess. random_int
was also introduced in PHP 7 and likewise uses a cryptographic random generator.
Many other solutions for random value generation, including those involving time()
, microtime()
, uniqid()
, rand()
, mt_rand()
, str_shuffle()
, array_rand()
, and shuffle()
, are much more predictable and are unsuitable if the random string will serve as a password, a bearer credential, a nonce, a session identifier, a "verification code" or "confirmation code", or another secret value.
The code above generates a string of 20 hexadecimal characters (0 to 9, or A to F). If you want to use a bigger character set (such as all upper-case letters, all lower-case letters, and the 10 digits), this is a more involved process, but you have to use random_int
rather than rand()
, mt_rand()
, str_shuffle()
, etc., if the string will serve as a password, a "confirmation code", or another secret value. See an answer to a related question.
I also list other things to keep in mind when generating unique identifiers, especially random ones.

- 32,158
- 14
- 82
- 96