'generating a random code in php?

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



Solution 1:[1]

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; 

} 

Solution 2:[2]

What about something like this, for ease:

$pass = substr(md5(uniqid(mt_rand(), true)) , 0, 8);

Solution 3:[3]

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.

Solution 4:[4]

<?php 

$uniqid = uniqid();

$rand_start = rand(1,5);

$rand_8_char = substr($uniqid,$rand_start,8);

?>

Solution 5:[5]

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
    ]
);

Solution 6:[6]

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.)

Solution 7:[7]

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;
}

Solution 8:[8]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eriksv88
Solution 2 Jeremy
Solution 3 Abhi
Solution 4
Solution 5
Solution 6 mario
Solution 7 Sean Vieira
Solution 8