PHP: Random string with numbers and letters

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:

There is an easier way to do this with a single line of code but you won’t have as much control over the characters that you want to include/exclude from the random PHP string. Here it is:

Comments

  1. Jim on January 10, 2011

    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 /////////////////////////////////////////

    Reply
  2. ? on January 20, 2011

    uniqid(”,true);
    more elegant.

    Reply
  3. JoeShmoe on February 1, 2011

    Awesome snippet, easy and good

    Reply
  4. Matt on February 11, 2011

    A nice clean and simple solution, thank you.

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

    Reply
  5. pennyauction on February 14, 2011

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

    Reply
  6. Sarah on February 22, 2011

    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!

    Reply
  7. Ben Borja on February 23, 2011

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

    Reply
  8. shane on February 25, 2011

    nice code man
    sweet and short

    Reply
  9. Neil on March 10, 2011

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

    Reply
  10. laittg on March 26, 2011

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

    Reply
  11. jaime on March 29, 2011

    nice I like this 🙂

    Reply
  12. takuhi on May 27, 2011

    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.

    Reply
  13. kukunkz on June 8, 2011

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

    Reply
  14. sid on June 17, 2011

    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

    Reply
  15. den on June 19, 2011

    thank you bro, i used it now.. 🙂

    regards

    Reply
  16. Starfire on June 28, 2011

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

    Reply
  17. Starfire on June 28, 2011

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

    Reply
  18. Alireza on July 2, 2011

    Thank you for the function.

    Reply
  19. Zach on July 2, 2011

    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…

    Reply
  20. Risingfalcon on July 15, 2011

    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

    Reply
  21. priyanka on August 10, 2011

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

    Reply
  22. Aditya on August 21, 2011

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

    Reply
  23. Eric on August 22, 2011

    Thanks, VERY simple.

    Reply
  24. Jack on August 31, 2011

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

    Reply
  25. ddart on August 31, 2011

    thank’s, good tutorial 🙂

    Reply
  26. Ali Rizwan on September 5, 2011

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

    Reply
  27. Lutashi on September 16, 2011

    Why not just use uniqid() ?

    Reply
  28. saumil on October 5, 2011

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

    Reply
  29. vebri dores on October 14, 2011

    coba ini:

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

    Reply
  30. arif on October 14, 2011

    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……..??

    Reply
  31. nitin on October 19, 2011

    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

    Reply
  32. […] 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/ […]

    Reply
  33. cuong1014 on October 26, 2011

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

    Reply
  34. Carlos on November 3, 2011

    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

    Reply
  35. Matthias on November 4, 2011

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

    Reply
  36. Eddie Dounn on November 14, 2011

    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;

    Reply
  37. LH on December 1, 2011

    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.

    Reply
  38. pictures on December 4, 2011

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

    Reply
  39. Eben on December 13, 2011

    Thanks dude! I’m going to use this.

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

    Reply
  41. psychotech on January 8, 2012

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

    Reply
  42. Nicholas Pickering on February 17, 2012

    I’ve done some benchmarking on both methods discusses here. At a length of 100 characters, it seems the base_encode64 method runs at half the speed as the OP’s method, but the string produced by the base_encode method seems to not produce technically (pseudo)random strings… For example, the string always seems to start with an M, N, or O, and consists mostly of capital letters. The OP’s method also allows you to control which characters are allowed into the random string, which is a plus for myself.

    Reply
  43. Nicholas Pickering on February 17, 2012

    *correction:

    I previously wrote it runs at half the speed, I meant it runs in half of the time.

    The base_encode method is much faster than OP method, but OP method is more customizable and reliable.

    Reply
  44. joschmo on February 24, 2012

    Modified a bit to this,works well for me. Prevents all-number and 0-length string from being returned. I don’t know if the quote marks will show up correctly on here when this is posted, so keep that in mind.
    function random_string($length=8,$string=””)
    {
    $length = $length < 1 ? 1 : $length;
    $string .= substr(md5(crypt(rand(0,10))),0,$length);
    $string = is_numeric($string) ? random_string($length,$string) : $string;
    return $string;
    }

    Reply
  45. Wale on March 26, 2012

    Found this through google. Very useful. Thanks very much.

    Here is how i used it:

    //creates random password
    $rands = substr(base64_encode(rand(1000000000,9999999999)),0,10);

    //encrypt password
    $rand_password = md5($rands);

    Its saves the encrypted password on the database and emails the unencrypted pw to the user, who then changes it after they have logged in. Really useful for the forget password function

    Reply
  46. Dhaval on December 10, 2012

    Hi,

    Thanks for clean snippet,its good. I’ve created one test file to test this function but I’m getting below Notice sometime.

    Notice: Uninitialized string offset: 36 in D:\xampp\htdocs\test\test.php on line 10

    We have several ways to hide the notice but I want to know the reason for that or it may help you if snippet need to correct something.

    Reply
  47. tim on March 31, 2013

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

    Reply
    • Antonie Potgieter on March 31, 2013

      Thank you for your input on this ill give it a go

      Reply
      • tim on April 1, 2013

        You’re welcome!

        You might also want to consider changing the function to:
        function genRandomString($length=10, $characters = “0123456789abcdefghijklmnopqrstuvwxyz”){
        instead of the staticly decleared vars.

        Reply
  48. Daniel Schaefer on April 3, 2014

    A little tip… if you calculate the value of strlen before the loop, it will save performance.

    Reply
    • Antonie Potgieter on April 3, 2014

      Thanks for your comment and tip, I’m sure it will be useful to readers here.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join our mailing list to receive the latest news and updates from our team.

You have Successfully Subscribed!

%d bloggers like this: