14

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?

AKor
  • 8,550
  • 27
  • 82
  • 136

3 Answers3

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

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

    return $string;
}
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 1
    It would be good to know collision distribution for this scheme. From the limited tests I have run it looks like for N characters, collisions happen after 10^(N-1) tries. Like, if you use 4 chars then collisions will happen after 1000 tries so you should be good for 100 tries at least. – rjha94 Dec 13 '11 at 05:44
  • 2
    It's random so every character has the same change - i.e. the longer the string the higher the chance of a duplicate character. – ThiefMaster Dec 13 '11 at 11:00
  • 1
    I do not think so because here the characters you pick have bias (of mt_rand). Say we were picking two char words. You will hit duplicates much before you expect. you have to consider probability distribution of mt_rand here. it is not a fair draw here. – rjha94 Dec 13 '11 at 13:49
  • @ThiefMaster Can you please explain the logic? – tuk Jan 21 '16 at 11:27
  • What would be a good way to speed this up? I have a use case where this must be used to modify millions of fairly long Unicode strings (~1000 - 2000 chars), but it takes 10 hours to process. – Juha Untinen Jun 12 '19 at 10:10
5
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
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
2
// $permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

echo 'm-'.substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 16).'.jpg';

// Output: m-swm3AP8X50VG4jCi.jpg
Vasin Yuriy
  • 484
  • 5
  • 13