PHP: Random string with numbers and letters

Mon, Oct 1, 2007

PHP

I thought that some of you might find it useful to learn how to generate a random string or a random number with PHP. I wrote a quick function to use PHP to generate random. See it below :

function genRandomString() {
    $length = 10;
    $characters = ’0123456789abcdefghijklmnopqrstuvwxyz’;
    $string = ;    

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

    return $string;
}

, , , , , , , , , , , , , ,
questions-widejpg

This post was written by:

- who has written 71 posts on Lost-In-Code.

I (Antonie Potgieter) am a software engineer/web developer located in South Africa. My full-time work is the management of Tribulant Software and the development of its software packages.

Contact the author

88 Comments For This Post

  1. Jake Holman Says:

    Nice, came across this with a quick google search.

    You have some syntax incorrect though. As it is now it will return something like 1f’q4w’432″2 – You don’t want those odd characters in there right?

    Remove $string = “; it will get defined anyway. Also replace the ‘ around the $characters declaration and replace it with ” – it should look like this:

    $characters = “0123456789abcdefghijklmnopqrstuvwxyz”;

    That will mean the return will only have letters and numbers ;)

  2. lost-in-code Says:

    Hi Jake,

    Thank you for the comment.

    It is the encoding of WordPress which causes those entities.
    In reality, you have to replace them with proper html characters when you use the code. Here is a sample :

    http://lost-in-code.com/wp-content/_randomstring.php

    It works well.

    All the best,
    Antonie

  3. Jake Holman Says:

    Oh then I do apolosgize! Didn’t consider WP might be screwing things up.

    But thank you for the snippet there. I used it in http://www.jakeisonline.com/s/ – something I was working on for work.

    Thanks!

  4. Eric Says:

    Also found this via google. Nice function, just wanted to drop a line and say thanks, I used this for my blog.

  5. Ryan Says:

    Thanks for the clip, nice and clean!

    -Ryan

  6. Brad Hanson Says:

    Shouldn’t it be strlen()-1 instead of strlen()?

    mt_rand() will sometimes return int $max and there isn’t a proper value in $characters[strlen()]

  7. Erwin Says:

    Great, thanks.

  8. Brandon Says:

    I think I was running into the issue that Brad was referring to. Another easy solution I found is just putting in the number 35 in place of strlen($characters). Essentially equal to Brads thought (36 characters -1).

  9. Generic Guy In Trenchcoat Says:

    That is a nice little peice of code. Most of these types of scripts are a little unweildly. Here is a slightly modified version that compensates for the length of $charachters. Except for the fact that I add a prefix to the string it functions the same and does not give off any log errors.

    function genRandomString() {
    $length = 7;
    $characters = “0123456789ABCDEFGHIJKLMNOPQRSTUVWZYZ”;
    $real_string_legnth = strlen($characters) – 1;
    $string=”ID”;

    for ($p = 0; $p < $length; $p++) {
    $string .= $characters[mt_rand(0, $real_string_legnth)];
    }
    return $string;
    }

    echo genRandomString();

  10. Dogukan Says:

    Thanks for the function.

  11. Ben Says:

    Hi,

    You have to change the line to:

    [code]
    $string .= $characters[mt_rand(0, strlen($characters)-1)];
    [/code]

    or else it will index out of bounds.

    Generic guy also made reference to this in his modified function.

  12. John James Jacoby Says:

    Found this on a Google search too. Thanks for the tip!

  13. Hank Knight Says:

    This is much more efficient; it uses a fraction of the memory and processing time. Try it!

  14. Hank Knight Says:

    echo substr(base64_encode(rand(1000000000,9999999999)),0,10);

  15. Madhupa Santra Says:

    Thanks…useful code.

  16. SP Says:

    Brilliant Knight. 1000x cleaner.

  17. F-3000 Says:

    Nice lil code. I only wish the original writer would fix the bugs.

  18. Pado Says:

    I just changed it a tiny bit and it worked perfectly. No bugs.
    Change $string = “; to $string = “”;
    Thanks for the nice code!

  19. F-3000 Says:

    Pado,

    Check Ben’s comment, and you might figure out what the bug really is.

    Also, Hank Knight’s code is a lot cleaner compared to the original post, but when comparing the outputs, Potgieter’s method produces a lot more random string.

  20. Mobile Addict Says:

    Bumped here via google, The discussed codes are really nice. Very useful in a bot harveters killer script.

  21. propellerhead Says:

    great function !

    here’s a good one:

    try this

    substr(md5(uniqid()), 0,10)

  22. Alex Says:

    Propellerhead’s method above gives the most random results.

    Thank you for the post.

    And the most compact!

    Alex, Programmer, London

  23. Alex Says:

    Properllerhead’s post yields strings of up to 13 characters.

    For longer strings (up to 23 characters) use

    substr(md5(uniqid(mt_rand(), true)), 0, );

    See the PHP Manual pages at:

    http://www.php.net/manual/en/function.uniqid.php

    and the W3Schools page at:

    http://www.w3schools.com/PHP/func_misc_uniqid.asp

    MODERATOR: can you merge this and my previous post please.

    Regards,

    Alex, London

  24. Joe Longstreet Says:

    Nice little method. I’m adding it to my codeigniter application right now.

  25. Utsav Singh Rathour Says:

    Thanks!!!
    This helped a lot. n ya i did follow the first comment and it helped too..

  26. Nilton Bicalho Says:

    function genRandomString($length=10, $string=”") {
    $characters = “0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
    for ($p = 0; $p < $length; $p++) $string .= $characters[mt_rand(0, strlen($characters))];
    return $string;
    }

  27. RM Says:

    Oulike stukkie kode.

  28. Rhys Thomas Says:

    None of these work!!!! they all product random strings that contain ” or ‘. Who wants that?!?

  29. Robbie Says:

    Hey Rhys,

    Try this:

    function randLetter()
    {
    $int = rand(0,51);
    $a_z = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”;
    $rand_letter = $a_z[$int];
    return $rand_letter;
    }

    It worked for me just great. :)

    Robbie

  30. TibTibs Says:

    for($i=0,$s=’abcdefghijklmnopqrstuvwxyz’.($_GET['upper']?’ABCDEFGHIJKLMNOPQRSTUVWXYZ’:”).($_GET['num']?’0123456789′:”).($_GET['sym']?’`-=[]\;,./~!@#$%^&*()_+{}|:”?’.”‘”:”);$i0?strlen($s)-1:25)];
    echo str_replace(array(”),array(‘<’,'>’),$p);

    Do I win? :) Enjoy my dirty coding lol.

    http://yoursite.com/PasswordGenie.php?len=40&sym=true&upper=true&num=true

  31. TibTibs Says:

    Bottom line got messed up in submission, this should show up correctly.

    echo str_replace(array(‘<’,'>’),array(‘&lt;’,'&gt;’),$p);

  32. TibTibs Says:

    Previous version was missing < > in symbols section, sorry :( … not used to posting in forums obviously. Feel free to delete my last two posts mr moderator man…

    for($i=0,$s=’abcdefghijklmnopqrstuvwxyz’.($_GET['upper']?’ABCDEFGHIJKLMNOPQRSTUVWXYZ’:”).($_GET['num']?’0123456789′:”).($_GET['sym']?’`-=[]\;,./~!@#$%^&*()_+{}|:”<>?’.”‘”:”);$i0?strlen($s)-1:25)];
    echo str_replace(array(‘<’,'>’),array(‘&lt;’,'&gt;’),$p);

  33. TibTibs Says:

    Alright, That wasn’t satisfactory to me, obviously I like compact coding… And the str_replace wasn’t neccessary… As well as declaring $s with each loop… and maybe more, heck if I remember.

    for($i=0,$s=’abcdefghijklmnopqrstuvwxyz’.($_GET[upper]?’ABCDEFGHIJKLMNOPQRSTUVWXYZ’:”).($_GET[num]?’0123456789′:”).($_GET[sym]?’`-=[]\;,./~!@#$%^&*()_+{}|:”<>?’.”‘”:”);$i<$_GET[len];$i++)echo htmlentities($s[rand(0,$i?strlen($s)-1:25)]);

    And to call it…
    http://yoursite.com/PasswordGenie.php?len=40&sym=1&upper=1&num=1

    I swear I'm done now :)

  34. Alder Cass Says:

    Thanks very much for this! Using it for renaming uploaded image files. I’d originally just set it to rename them to a random number between 1 and a million but this HUGELY reduces the odds of duplicate file names.

  35. lk Says:

    Should be:

    strlen($characters)-1)

  36. Wll Says:

    Hello,

    This is the script I needed to implement at http://www.bleidu.com, very quickly and easily.

    Not to bad for a confirmation code!

    Thanks.

  37. bernard Says:

    $pass = substr(md5(rand(1001,5000)),6,5);

    That’s how I did it for my site http://www.tipsonhowtomakemoney.com, simple and easy :)

  38. di3Z3L Says:

    Hello, I’ve put my own logic into it. I think someone might find it useful, it’s pretty fast. Here’s the function (hope it will be readable somehow, presuming that tag is unsupported):

    function get_random_string($length = 8, $numbers = true, $upper = true)
    {
    if (1 > $length) $length = 8;

    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $numChars = 62;

    if (!$numbers)
    {
    $numChars = 52;
    $chars = substr($chars, 10, $numChars);
    }

    if (!$upper)
    {
    $numChars -= 26;
    $chars = substr($chars, 0, $numChars);
    }

    $string = '';

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

    return $string;
    }

    get_random_string() // both cases and numbers
    get_random_string(8, false) // both cases, numbers excluded
    get_random_string(8, false, false) // just lower case
    get_random_string(8, true, false) // lower case and numbers

  39. Arif Says:

    FINAL solution ! NO more problems – everything sorted and tested – just coypy & paste with notice below. thanks.

    //– Improved by Arif. Random password string generator – WORKs GREAT!!
    /== Original by Antonie Potgieter @ http://www.lost-in-code.com/author/admin/
    //– Please Include this 3-line notice if using it in you code. ——-

    //== Original Function by Antonie Potgieter at
    //== http://www.lost-in-code.com/author/admin/ =====

    //**** Generate a random password / string **********
    //**** Change string contents as required **********
    //**** strlen() now as should be corrected by -1 ***

    function genRandomString($size)
    {
    $length = $size;
    $characters = ‘!”£$%^&*(){}-=+:;@~#|0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWZYZ’;
    $string = ”;

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

    return $string;
    }

    echo "– This run generated string: *".genRandomString(12)."* –";
    // —— or call by funtion as , $string = genRandomString(x).
    // —— where x is an integer of the required string length .

  40. lucky Says:

    a little change, to get more flexibility:

    function genRandomString($length = 10) {
    $characters = ’0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ’;
    $string = ”;
    for ($p = 0; $p < $length; $p++) {
    $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
    }

    Thank you very much!!

  41. helper Says:

    WARNING ATTENTION CAUTION IMPORTANT ERROR PROBLEM:
    there’s 2 problems!
    firstly, it should be:
    $string .= $characters[mt_rand(0, strlen($characters) - 1)];

    and secondly, the “$character = …” line DOESN’T USE CORRECT QUOTATION SYMBOL. it uses ’ instead of ‘ or ” – so careful when you copy paste – be sure to change it.
    i didn’t copied that weird tick and kept getting errors in the form of strange characters.

  42. Mahboob Says:

    Error Message: Uninitialized string offset: 36

  43. Exclusive Says:

    Thanks for the script (: Seems that what lucky did (2 posts above) also works nicely and like he suggested, it does allow more flexibility. Having edited the script to allow users to change the string length by letting them enter a number into a variable, it now works amazing :D

    thanks for sharing (:

  44. DC Says:

    I’m not a pro but this seems to work. Change the number to set the length of the string.

  45. chandu Says:

    Thanks for function concept………

  46. Eka Says:

    Hmm i didnt see any examples of the chr() function which does almost the same thing in a consise format if the goal is just to generate a random string with letters upper case and lower case and numbers the ranges of ch() can be found here so you could modify this code with special chars. You can see the associated range here http://www.asciitable.com/ so to generate a random lower case letter just use chr(rand(97,122)) or put this in a loop with the length needed i normally add a layer of randomness with the following function to create strings of 15 mixed alphanumerics
    function genRandom($l){
    function charType(){
    $r = rand(1,3);
    switch($r){case 1: return chr(rand(97,122)); break;case 2: return chr(rand(65,90)); break; case 3: return chr(rand(48,57)); break;}
    }
    for($i;$i<=$l;$i++){ $random.=charType().charType().charType();}
    return $random;
    }
    $str = genRandom(5);

  47. Matheus Says:

    Simple, but complete. Thank you

  48. Febin Joy Says:

    Thanks,
    Nice little method. I have to use it into my application right now.

  49. SilentJoker Says:

    This is what i used so its #A#A

    function idgen($length)
    {
    $validCharacters1 = “0123456789″;
    $validCharacters2 = “ABCDEFGHIJKLMNOPQRSTUXYVWZ”;

    $result1 = “”;
    $result2 = “”;
    $p=0;
    for ($i = 0; $i < $length; $i++)
    {
    if($p==0)
    {
    $result .= $validCharacters1[mt_rand(0, strlen($validCharacters1 -1))];
    $p++;
    echo "$p";
    }
    else
    {
    $result .= $validCharacters2[mt_rand(0, strlen($validCharacters2 -1))];
    $p–;
    echo "$p";
    }
    }
    return $result;
    }

  50. Jim Says:

    Using a random number to be included with another character. Then I want to strip out the random number and just leave the other character. I have this code that generates the random number (8 characters long) consistently. If you hit your refresh button multiple times, the “ID” field disappears even though the “Random Number” plus “ID” are still there. Not sure what is happening to the random number on refresh in the substr function. This is the code:

    // Begin Create Random ID Code /////////////////////////////////////////

    function gRanStr1() {
    $length1 = 8;
    $characters = “0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”;

    for ($p = 0; $p < $length1; $p++) {
    $lcrs1 .= $characters[mt_rand(0, strlen($characters)-1)];
    }

    $lcrs9 = str_replace(' ', '', $lcrs9);

    return $lcrs1;

    }

    // End Create Random ID Code /////////////////////////////////////////

    // Begin Decode Random ID Code /////////////////////////////////////////

    $TrkR99 = "c";

    $ResHeadID = gRanStr1() . $TrkR99;

    $ResHeadID = preg_replace('/[\s]+/',' ',$ResHeadID);

    echo "”;
    echo $ResHeadID . ” = echo of Random Number plus ID“;

    for($i=0; $i<strlen($ResHeadID); $i++){
    if(!is_numeric(substr($ResHeadID, $i, 1))){
    $Index1 = $i;
    break;
    }
    }

    if ($ResHeadID == "") {
    "";
    } else {
    $ResHeadID = preg_replace('/[\s]+/',' ',$ResHeadID);
    $TrkRa1 = substr($ResHeadID, $Index1 + 8, 1);
    }

    $dTrkRes = $TrkRa1;

    echo $TrkRa1 . " = echo of ID after random number stripped.“;

    echo “”;

    // End Decode Random ID Code /////////////////////////////////////////

  51. ? Says:

    uniqid(”,true);
    more elegant.

  52. JoeShmoe Says:

    Awesome snippet, easy and good

  53. Matt Says:

    A nice clean and simple solution, thank you.

    I replaced the ‘ with ” as I prefer to use double quotes for strings in php.

  54. pennyauction Says:

    Great script, how do I make a random number signed number string? can the value of mt_rand() minimum be a negative number?

  55. Sarah Says:

    Thanks for the script, it was really useful for a project I’m working on.

    I found that something the random string was one character less than what was set as $length, but after reading the comments I added -1 to the strlen($characters) and now it always return the correct amount of characters.

    Thanks again!

  56. Ben Borja Says:

    Thanks for this quick code. Used it for an email activation link.

  57. shane Says:

    nice code man
    sweet and short

  58. Neil Says:

    Thanks so much. You would not believe how complicated some other solutions I have seen are. Using this on my site now.

  59. laittg Says:

    Found this by Google, a lightweight and useful function.

    I modified a little:

    //Generate random password. $c = quantity of character. $n = quantity of numeric.
    function random_password($c, $n) {
    $chars = “abcdefghijklmnopqrstuvwxyz”;
    $clength = strlen($chars);

    $nums = “123456789″;
    $nlength = strlen($nums);

    $string = “”;
    for ($i = 0; $i < $c; $i++) $string .= $chars[mt_rand(0, $clength)];
    for ($i = 0; $i < $n; $i++) $string .= $nums [mt_rand(0, $nlength)];

    return $string;
    }

  60. jaime Says:

    nice I like this :)

  61. takuhi Says:

    Like everyone else I found this via Google.

    Although the script is okay, and it does create a very random string, I have to agree with bernard, propellerhead, Alex etc. that using something like md5 is just a simpler way of doing it.

    I did a bit of testing and the following bit of code (which has been suggested before) is by far the fastest :

    echo substr(md5(rand(0,10)),0,20);

    If you want to trade speed for an even more random sample, try :

    echo substr(md5(crypt(rand(0,10))),0,20);

    This still creates a random 20 character string in about 0.003 seconds.

    Arguably using the crypt() function is far more secure and random. As a whole you get three random elements, md5, crypt and a random number between 0 and 10.

    Note : Increasing the initial random number seed size to whatever you like makes absolutely no impact on performance. It really depends on how ‘random’ you want it.

    Thanks for the script though, Potgieter. Without it I wouldn’t have done my own bit of research.

  62. kukunkz Says:

    thx for the tutorial … it works nice …thx…a lot brothers

  63. sid Says:

    thank u for this… this has helped me solve one of buddypress’s most talked about issues… of randomly generating an avatar pic form a custom set of pictures…. thank you

    i used it in combination with another piece of code.. but yours was the missing link… the other one has been out there since forever.

    http://buddypress.org/community/groups/how-to-and-troubleshooting/forum/topic/custom-set-of-avatar-pics/#post-101775

    sid

  64. den Says:

    thank you bro, i used it now.. :)

    regards

  65. Starfire Says:

    Hy!

    I need some help with the code.
    I have an account manager script and want to implent init.

    The problem is when U complete a registration its working wo a problem but the random chars are not generated or (dont know) just not stored in mysql.

    I placed in the script like this.

    {
    $res = mysql_query(“SELECT * FROM accounts WHERE login = ‘”.$name.”‘”) or die(“ADATBAZIS HIBA!”);
    if (mysql_num_rows($res))
    $message = “Sajnos ez az accunt név már foglalt.Kérlek válassz másikat.Újra.“;
    else
    {
    {
    function genRandomString() {
    $length = 10;
    $characters = “0123456789abcdefghijklmnopqrstuvwxyz”;

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

    return $string;
    }
    mysql_query("INSERT INTO accounts (login, password, lastactive, access_level, lastServer, email, regdate, actcode) VALUES ('".$name."', '".base64_encode(pack("H*", sha1(utf8_encode($pwd1))))."', '0', '-100', '1', '".$mail."', '".date("Y/m/d H:i:s")."', '".$string."')") or die("ADATBAZIS HIBA!");
    $message = " text ";
    }
    }
    "

  66. Starfire Says:

    I want to use it as an activation system its generate a code store it in sql and send it in email to the user.

    And when the user enter it in the activation script, its sets the accesslvl from -100 to 0.

    Sorry for my bad english. :)

  67. Alireza Says:

    Thank you for the function.

  68. Zach Says:

    Tons of great input here guys. Thanks to everyone for their additions, especially Propellerhead and Alex. It’s amazing what you can find through good ole google…

  69. Risingfalcon Says:

    Nice and sensible code :) .@First comment on this entry(Jake Holman), string=”" is necessary before the for loop because theres a ‘.=’ in the for loop and not a ‘=’ which means that it will fetch a predefined value of $string which is “” but it has SOME value and is NOT UNDEFINED =D

  70. priyanka Says:

    Thank you for code, but please help me to generate various strings on a single click.

  71. Aditya Says:

    Excellent Piece of Code…

    Just a slight modification

    replace

    $string .= $characters[mt_rand(0, strlen($characters))];

    with

    $string .= $characters[mt_rand(0, strlen($characters)-1)];

  72. Eric Says:

    Thanks, VERY simple.

  73. Jack Says:

    Hey nice snippet… Thanks… I used it in my code today… Thanks Again

  74. ddart Says:

    thank’s, good tutorial :)

  75. Ali Rizwan Says:

    Thanx for the snippet. This is exactly what i wanted.

  76. Lutashi Says:

    Why not just use uniqid() ?

  77. saumil Says:

    why � symbol appears in generated string.
    i want to remove it please help??

  78. vebri dores Says:

    coba ini:

    echo substr(md5(uniqid()), 0,16);

  79. arif Says:

    bagaimana yaa caranya buat nampilin hasil acak string sesuai dengan jumlah yang kita inginkan. misalnya pingin nampilin hasil acak random sebanyak 100 kali.dengan menggunakan 6 karakter pada string yang di acak……..??

  80. nitin Says:

    hey, i guess u shud b using it this way:

    $string .= $characters[mt_rand(1, strlen($characters)) - 1];

    That is, starting by 1, and till length-1 (36-1), else it gaves sum error smtyms related to array limits crossd

  81. cuong1014 Says:

    $random = substr(str_shuffle(str_repeat(‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789′,5)),0,$length)

  82. Carlos Says:

    Thank you guys this post really helped me!!!!!
    :) )

    But as a suggestion, you should allow the user to select the length from the function itself like this

    function genRandomString($length=null) {
    if($length==null){$length = 10;}
    $characters = ’0123456789abcdefghijklmnopqrstuvwxyz’;
    $string = ”;
    for ($p = 0; $p < $length; $p++) {
    $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
    }

    That way the user can choose the length from the function but if they don't want to, the function will default to 10

  83. Matthias Says:

    you should shuffle the seed as well, since mt_rand is not that strong and will generate collisions if you reach above 1.000.000 strings. As it happened to me while generating voucher codes.

    $characters = str_shuffle($characters);

  84. Eddie Dounn Says:

    thank you! I used your code! but not for wordpress

    function genRandomString() {
    $length = 10;
    $characters = “0123456789abcdefghijklmnopqrstuvwxyz”;
    for ($p = 0; $p < $length; $p++) {
    $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;

  85. LH Says:

    Is there a way to generate a string of random letters and numbers in an Excel format? I am not very saavy at this, and any help would be appreciated! Thanks.

  86. pictures Says:

    I found that quite easy to use, thanks for the easy method:)

  87. Eben Says:

    Thanks dude! I’m going to use this.

  88. psychotech Says:

    Great function! Thank you sir!
    To make it even cooler, make “length an optional parameter”!!!

3 Trackbacks For This Post

  1. Nebula Warp » Generate Random String Says:

    [...] need code to generate a random string, this is one particular piece of code I found a while back on Lost in Code, which I use all the time in PHP. Code Extract   function genRandomString() [...]

  2. Urheberrecht - Captcha-Code - Seite 3 - JuraForum.de Says:

    [...] Zitat von once Mit Hilfe welcher Programmierung geschieht bei Dir dieses "per Zufall" ( eine Zahl aus einer Menge { 1,2,3,4,5,7,8,9 } auswählen ) ? 11 eine möglichkeit für die zufällige ausgabe wäre diese: http://www.lost-in-code.com/programm…s-and-letters/ [...]

  3. PHP Random String Function | KC-TUTOR Says:

    [...] tutorial is based on Lost In Code - PHP Random String Function …. Posts Related to PHP Random String FunctionPHP String FunctionsString functios are used [...]

Leave a Reply