generating a random code in php?



PHP Snippet 1:

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; 

} 

PHP Snippet 2:

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

PHP Snippet 3:

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

PHP Snippet 4:

<?php 

$uniqid = uniqid();

$rand_start = rand(1,5);

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

?>

PHP Snippet 5:

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

PHP Snippet 6:

echo create_random_code(
    6,
    [
        'upper_case'        => true,
        'lower_case'        => true,
        'number'            => true,
        'special_character' => false
    ]
);

PHP Snippet 7:

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

PHP Snippet 8:

bin2hex(random_bytes(10))