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++) {
        $rand_string.=$string[rand(0,$len)];
    }
    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 (2) Add New Comment
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? 

Reply
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? 

Reply