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 :

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

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

    return $string;
}

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:

$string = substr(md5(microtime()), rand(0,99), 10);
  • http://www.nugstar.org Jim

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

  • http://google.com ?

    uniqid(”,true);
    more elegant.

  • JoeShmoe

    Awesome snippet, easy and good

  • http://www.freelancesoftwaredeveloper.co.uk Matt

    A nice clean and simple solution, thank you.

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

  • http://www.bid888.com pennyauction

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

  • http://www.designsheep.co.uk Sarah

    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!

  • Ben Borja

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

  • shane

    nice code man
    sweet and short

  • http://www.brighterwebsites.com.au Neil

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

  • laittg

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

  • jaime

    nice I like this :)

  • http://www.quick-grid.com takuhi

    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.

  • kukunkz

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

  • sid

    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

  • den

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

    regards

  • http://notonline Starfire

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

  • http://notonline Starfire

    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. :)

  • Alireza

    Thank you for the function.

  • http://zikkilocal.com/ Zach

    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…

  • Risingfalcon

    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

  • priyanka

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

  • Aditya

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

  • Eric

    Thanks, VERY simple.

  • Jack

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

  • ddart

    thank’s, good tutorial :)

  • Ali Rizwan

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

  • http://dachaocai.com Lutashi

    Why not just use uniqid() ?

  • saumil

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

  • http://produkdalamnegeri.com vebri dores

    coba ini:

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

  • arif

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

  • http://nitinbansal.info nitin

    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

  • Pingback: Urheberrecht - Captcha-Code - Seite 3 - JuraForum.de

  • http://www.google.com cuong1014

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

  • Carlos

    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

  • http://www.artofcode.de Matthias

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

  • http://howcanigetoutofdebt.net/ Eddie Dounn

    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;

  • LH

    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.

  • http://www.pikture.net pictures

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

  • Eben

    Thanks dude! I’m going to use this.

  • Pingback: PHP Random String Function | KC-TUTOR

  • psychotech

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

  • Nicholas Pickering

    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.

  • Nicholas Pickering

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

  • joschmo

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

  • http://wsalami.com Wale

    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

  • Dhaval

    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.

  • tim

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

  • http://tribulant.com/ Antonie Potgieter

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

  • tim

    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.