Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a unique random string of a certain length and restrictions in PHP?

Tags:

php

I have the need to generate a random alphanumeric string of 8 characters. So it should look sort of like b53m1isM for example. Both upper and lower case, letters and numbers.

I already have a loop that runs eight times and what I want it to do is to concatenate a string with a new random character every iteration.

Here's the loop:

$i = 0;
    while($i < 8)
    {
        $randPass = $randPass + //random char
        $i = $i + 1;
    }

Any help?

like image 884
AKor Avatar asked Mar 26 '11 19:03

AKor


2 Answers

function getRandomString($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $string = '';

    for ($i = 0; $i < $length; $i++) {
        $string .= $characters[mt_rand(0, strlen($characters) - 1)];
    }

    return $string;
}
like image 195
ThiefMaster Avatar answered Oct 21 '22 13:10

ThiefMaster


function randr($j = 8){
    $string = "";
    for($i=0; $i < $j; $i++){
        $x = mt_rand(0, 2);
        switch($x){
            case 0: $string.= chr(mt_rand(97,122));break;
            case 1: $string.= chr(mt_rand(65,90));break;
            case 2: $string.= chr(mt_rand(48,57));break;
        }
    }
    return $string; 
}

echo randr(); // b53m1isM
like image 21
Dejan Marjanović Avatar answered Oct 21 '22 14:10

Dejan Marjanović