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 :
$length = 10;
$characters = ’0123456789abcdefghijklmnopqrstuvwxyz’;
$string = ”;
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}








August 3rd, 2008 at 1:39 pm
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
August 3rd, 2008 at 1:54 pm
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
August 7th, 2008 at 5:07 pm
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!
August 31st, 2008 at 11:58 am
Also found this via google. Nice function, just wanted to drop a line and say thanks, I used this for my blog.
September 11th, 2008 at 10:21 pm
Thanks for the clip, nice and clean!
-Ryan
September 27th, 2008 at 1:06 am
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()]
October 17th, 2008 at 5:47 am
Great, thanks.
February 7th, 2009 at 10:15 pm
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).
March 11th, 2009 at 1:55 am
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();
March 14th, 2009 at 6:02 am
Thanks for the function.
April 3rd, 2009 at 5:51 pm
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.
April 25th, 2009 at 6:18 pm
Found this on a Google search too. Thanks for the tip!
May 19th, 2009 at 8:29 am
This is much more efficient; it uses a fraction of the memory and processing time. Try it!
May 19th, 2009 at 8:30 am
echo substr(base64_encode(rand(1000000000,9999999999)),0,10);
May 21st, 2009 at 5:16 am
Thanks…useful code.
August 3rd, 2009 at 11:53 am
Brilliant Knight. 1000x cleaner.
August 4th, 2009 at 4:16 am
Nice lil code. I only wish the original writer would fix the bugs.
August 7th, 2009 at 11:23 am
I just changed it a tiny bit and it worked perfectly. No bugs.
Change $string = “; to $string = “”;
Thanks for the nice code!
August 10th, 2009 at 2:32 pm
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.
August 15th, 2009 at 2:28 am
Bumped here via google, The discussed codes are really nice. Very useful in a bot harveters killer script.
September 16th, 2009 at 8:55 am
great function !
here’s a good one:
try this
substr(md5(uniqid()), 0,10)
September 17th, 2009 at 9:55 pm
Propellerhead’s method above gives the most random results.
Thank you for the post.
And the most compact!
Alex, Programmer, London
September 17th, 2009 at 10:33 pm
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
December 16th, 2009 at 10:41 am
Nice little method. I’m adding it to my codeigniter application right now.
March 14th, 2010 at 10:52 pm
Thanks!!!
This helped a lot. n ya i did follow the first comment and it helped too..
April 26th, 2010 at 11:25 am
function genRandomString($length=10, $string=”") {
$characters = “0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
for ($p = 0; $p < $length; $p++) $string .= $characters[mt_rand(0, strlen($characters))];
return $string;
}
May 17th, 2010 at 10:18 am
Oulike stukkie kode.
May 21st, 2010 at 1:05 pm
None of these work!!!! they all product random strings that contain ” or ‘. Who wants that?!?
May 28th, 2010 at 9:18 am
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
June 4th, 2010 at 7:13 am
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
June 4th, 2010 at 7:15 am
Bottom line got messed up in submission, this should show up correctly.
echo str_replace(array(‘<’,'>’),array(‘<’,'>’),$p);
June 4th, 2010 at 7:19 am
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(‘<’,'>’),$p);
June 4th, 2010 at 7:48 am
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
July 11th, 2010 at 7:00 pm
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.
August 2nd, 2010 at 7:21 am
Should be:
strlen($characters)-1)
August 14th, 2010 at 4:57 pm
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.
August 31st, 2010 at 7:17 am
$pass = substr(md5(rand(1001,5000)),6,5);
That’s how I did it for my site http://www.tipsonhowtomakemoney.com, simple and easy
August 31st, 2010 at 6:16 pm
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
September 19th, 2010 at 12:20 pm
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 .
September 19th, 2010 at 3:48 pm
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!!
September 20th, 2010 at 12:09 am
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.
September 23rd, 2010 at 9:55 am
Error Message: Uninitialized string offset: 36
September 26th, 2010 at 12:44 pm
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
thanks for sharing (:
October 25th, 2010 at 3:36 pm
I’m not a pro but this seems to work. Change the number to set the length of the string.
October 30th, 2010 at 8:34 am
Thanks for function concept………
November 3rd, 2010 at 12:12 am
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);
November 23rd, 2010 at 2:51 pm
Simple, but complete. Thank you
December 21st, 2010 at 4:11 am
Thanks,
Nice little method. I have to use it into my application right now.
December 31st, 2010 at 12:05 pm
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;
}
January 10th, 2011 at 10:43 pm
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 /////////////////////////////////////////
January 20th, 2011 at 4:24 pm
uniqid(”,true);
more elegant.
February 1st, 2011 at 4:37 pm
Awesome snippet, easy and good
February 11th, 2011 at 12:35 pm
A nice clean and simple solution, thank you.
I replaced the ‘ with ” as I prefer to use double quotes for strings in php.
February 14th, 2011 at 9:10 pm
Great script, how do I make a random number signed number string? can the value of mt_rand() minimum be a negative number?
February 22nd, 2011 at 5:35 am
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!
February 23rd, 2011 at 6:35 pm
Thanks for this quick code. Used it for an email activation link.
February 25th, 2011 at 8:00 am
nice code man
sweet and short
March 10th, 2011 at 9:03 am
Thanks so much. You would not believe how complicated some other solutions I have seen are. Using this on my site now.
March 26th, 2011 at 1:48 am
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;
}
March 29th, 2011 at 12:34 pm
nice I like this
May 27th, 2011 at 5:20 pm
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.
June 8th, 2011 at 6:58 pm
thx for the tutorial … it works nice …thx…a lot brothers
June 17th, 2011 at 4:53 pm
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
June 19th, 2011 at 1:33 am
thank you bro, i used it now..
regards
June 28th, 2011 at 7:32 am
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 ";
}
}
"
June 28th, 2011 at 8:01 am
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.
July 2nd, 2011 at 12:11 pm
Thank you for the function.
July 2nd, 2011 at 6:38 pm
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…
July 15th, 2011 at 4:21 pm
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
August 10th, 2011 at 6:13 am
Thank you for code, but please help me to generate various strings on a single click.
August 21st, 2011 at 3:05 am
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)];
August 22nd, 2011 at 11:47 am
Thanks, VERY simple.
August 31st, 2011 at 9:12 am
Hey nice snippet… Thanks… I used it in my code today… Thanks Again
August 31st, 2011 at 4:20 pm
thank’s, good tutorial
September 5th, 2011 at 1:22 am
Thanx for the snippet. This is exactly what i wanted.
September 16th, 2011 at 5:48 am
Why not just use uniqid() ?
October 5th, 2011 at 2:44 am
why � symbol appears in generated string.
i want to remove it please help??
October 14th, 2011 at 12:40 pm
coba ini:
echo substr(md5(uniqid()), 0,16);
October 14th, 2011 at 10:51 pm
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……..??
October 19th, 2011 at 5:33 pm
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
October 26th, 2011 at 9:26 am
$random = substr(str_shuffle(str_repeat(‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789′,5)),0,$length)
November 3rd, 2011 at 10:35 am
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
November 4th, 2011 at 3:59 am
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);
November 14th, 2011 at 8:33 pm
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;
December 1st, 2011 at 10:26 am
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.
December 4th, 2011 at 6:27 am
I found that quite easy to use, thanks for the easy method:)
December 13th, 2011 at 8:34 pm
Thanks dude! I’m going to use this.
January 8th, 2012 at 6:55 am
Great function! Thank you sir!
To make it even cooler, make “length an optional parameter”!!!