2018-11-10 Pujan Niroula 1 Minute(s) Read

Generate Random String in PHP

img-random string.png

Hello there,

We need to generate random string while developing web in PHP. Mostly for password, cookies, tokens etc.

Passwords, tokens, cookies, sessions should be uniquely generated string which should be difficult to crack else your web application will not be secure. So today I will show you how to create random string in PHP specially for passwords and cookies.

Generate Random Number in PHP

If you want to generate just numbers then this will be useful for you. Simply use rand function.

//rand(start_int, end_int) or just rand();
echo rand(0,100);

This will Generate random number between 0 and 100. If you want to generate complex number then increase range for eg. rand(1000000,99999999999); Let's see result:

Generate rand num

Generate Random AlphaNumeric String in PHP

You learned to create simple random number generator and want to learn more? Lets generate random alpha-numeric string in PHP.

$alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
$count = str_count($alpha);
echo $alpha[rand(0,$count)]; //This will echo random letter;
//Lets repeat this
echo $alpha[rand(0, $count)].$alpha[rand(0, $count)];

Random String of Fixed Length Generator in PHP

Let's generate complex and secure value for real world. This will generate random string which can be used as your password, session or cookies without worrying about bruteforce or guessing.

function rand_string($length)
    $string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%&*_.";
    $len = strlen($string)-1;
    $rand_string ='';
    for ($i=0; $i < $length; $i++) {
    return $rand_string;

Now you call the function with desired random string for eg. if you want 8 digits random string then use rand_string(8).

PHP Random string result

Cons about this random password/string generator is you might get repeated character. Let's fix it too.

Create Random String with Unique Characters in PHP

In this method I will show how can you create random string for password or anything without using rand function. Most amazing feature of this is it will create random string without repeated characters. Let's make it...

function alt_rand_pass($length)
    $string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%&*_.";
    $shuffled = str_shuffle($string); //It will shuffle the string
    $rand = substr($shuffled,0,$length); //return the part of string from 0 to length
    return $rand;

Okay, In this example I did not used rand function. I just shuffled the string and got the random value suitable for password. Each time the function will displays different output because it shuffle the $string.

Final Words

You can use any of above methods according to your need. And from this post you learned about different useful PHP functions such as rand, strlen, str_shuffle etc.

Keep learning and Comments are welcomed!

Download Attached Files: PHP Random String Generator.zip
Tags:how to, php,
Comments (4) Add New Comment
Lhanekix2024-06-25 2:12 AM

Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something. I think that you could do with a few pics to drive the message home a little bit, but instead of that, this is magnificent blog. A fantastic read. I will certainly be back. himchistka.udm.ru/forum?%2Fforum=&%2Fforum%2F=&GuestbookItem_page=11  5-5.ru/index.php?links_exchange=yes&page=501&show_all=yes  suamaylanh.com.vn/tin-tuc/40-hang-dien-tu-dien-lanh-ton-nhieu.html  politikforum.ru/member.php?u=13387008  lolipopnews.ru/page/9 

OLanekix2024-06-20 12:00 AM

Wow that was unusual. I just wrote an really long comment but after I clicked submit my comment didn't appear. Grrrr... well I'm not writing all that over again. Anyhow, just wanted to say wonderful blog! premiumkutyatap.hu/jutalom_pontok  hokutosite.com/bbs/yybbs.cgi?pg=60  darknews.ru/page/34  myfootballday.ru/page/14  venturetraining.net/tag/return-on-investment/ 

Ismaeleromo2024-06-10 8:55 AM

That is really attention-grabbing, You're a very skilled blogger. I've joined your feed and stay up for in search of extra of your excellent post. Additionally, I've shared your website in my social networks beritanusantara.co.id/cadir-polimdo-okta-lintong-efendy-rasid-maryke-alelo-masuki-tahap-pertarungan-tingkat-kementerian/?  petrovsky-hotel.ru/booking/?arrival-date-offset=1&nights=1&room-type=10945?  forum.mbprinteddroids.com/showthread.php?tid=1087&pid=1351&mode=threaded?  2xaynha.com/2014/09/18?  newsbizlife.ru/page/5? 

Ismaeleromo2024-06-09 9:38 PM

Hi it's me, I am also visiting this site daily, this site is actually fastidious and the people are genuinely sharing pleasant thoughts. buzzchatlive.com/index.php?do=/public/user/blogs/name_Alanpoe/page_7/?  delivery-containers.ru/news/dvzhd-v-i-polugodii-uvelichila-pogruzku-kontejjnerov-na-74/?  kamagraopas.com/mitka-ovat-varotoimenpiteetvaroitukset-kamagraan-liittyen.html?  americanautotitleloan.com/lake-wylie-sc-title-loans?  kenhhocsinh.com/tai-sao-ly-thuong-kiet-lai-ket-thuc-cuoc-khang-chien-chong-tong-bang-bien-phap-giang-hoa?