Skip to main content

How to Generate PHP Random String Token (8 Ways)

 Generating random string token may sound like a trivial work. If you really want something “truly random”, it is one difficult job to do. In a project where you want a not so critical scrambled string there are many ways to get it done.

I present eight different ways of getting a random string token using PHP.

  1. Using random_int()
  2. Using rand()
  3. By string shuffling to generate a random substring.
  4. Using bin2hex()
  5. Using mt_rand()
  6. Using hashing sha1()
  7. Using hashing md5()
  8. Using PHP uniqid()

There are too many PHP functions that can be used to generate the random string. With the combination of those functions, this code assures to generate an unrepeatable random string and unpredictable by a civilian user.

1) Using random_int()

The PHP random_int() function generates cryptographic pseudo random integer. This random integer is used as an index to get the character from the given string base.

The string base includes 0-9, a-z and A-Z characters to return an alphanumeric random number.

Quick example

<?php
/**
 * Uses random_int as core logic and generates a random string
 * random_int is a pseudorandom number generator
 *
 * @param int $length
 * @return string
 */
function getRandomStringRandomInt($length = 16)
{
    $stringSpace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $pieces = [];
    $max = mb_strlen($stringSpace, '8bit') - 1;
    for ($i = 0; $i < $length; ++ $i) {
        $pieces[] = $stringSpace[random_int(0, $max)];
    }
    return implode('', $pieces);
}
echo "<br>Using random_int(): " . getRandomStringRandomInt();
?>

php random string

2) Using rand()

It uses simple PHP rand() and follows straightforward logic without encoding or encrypting.

It calculates the given string base’s length and pass it as a limit to the rand() function.

It gets the random character with the random index returned by the rand(). It applies string concatenation every time to form the random string in a loop.

<?php
/**
 * Uses the list of alphabets, numbers as base set, then picks using array index
 * by using rand() function.
 *
 * @param int $length
 * @return string
 */
function getRandomStringRand($length = 16)
{
    $stringSpace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $stringLength = strlen($stringSpace);
    $randomString = '';
    for ($i = 0; $i < $length; $i ++) {
        $randomString = $randomString . $stringSpace[rand(0, $stringLength - 1)];
    }
    return $randomString;
}
echo "<br>Using rand(): " . getRandomStringRand();
?>

3) By string shuffling to generate a random substring.

It returns the random integer with the specified length.

It applies PHP string repeat and shuffle the output string. Then, extracts the substring from the shuffled string with the specified length.

<?php
/**
 * Uses the list of alphabets, numbers as base set.
 * Then shuffle and get the length required.
 *
 * @param int $length
 * @return string
 */
function getRandomStringShuffle($length = 16)
{
    $stringSpace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $stringLength = strlen($stringSpace);
    $string = str_repeat($stringSpace, ceil($length / $stringLength));
    $shuffledString = str_shuffle($string);
    $randomString = substr($shuffledString, 1, $length);
    return $randomString;
}
echo "<br>Using shuffle(): " . getRandomStringShuffle();
?>

4) Using bin2hex()

Like random_int(), the random_bytes() returns cryptographically secured random bytes.

If the function doesn’t exists, this program then uses openssl_random_pseudo_bytes() function.

<?php
/**
 * Get bytes of using random_bytes or openssl_random_pseudo_bytes
 * then using bin2hex to get a random string.
 *
 * @param int $length
 * @return string
 */
function getRandomStringBin2hex($length = 16)
{
    if (function_exists('random_bytes')) {
        $bytes = random_bytes($length / 2);
    } else {
        $bytes = openssl_random_pseudo_bytes($length / 2);
    }
    $randomString = bin2hex($bytes);
    return $randomString;
}
echo "<br>Using bin2hex(): " . getRandomStringBin2hex();
?>

5) Using mt_rand()

PHP mt_rand() is the replacement of rand(). It generates a random string using the Mersenne Twister Random Number Generator.

This code generates the string base dynamically using the range() function.

Then, it runs the loop to build the random string using mt_rand() in each iteration.

<?php
/**
 * Using mt_rand() actually it is an alias of rand()
 *
 * @param int $length
 * @return string
 */
function getRandomStringMtrand($length = 16)
{
    $keys = array_merge(range(0, 9), range('a', 'z'));
    $key = "";
    for ($i = 0; $i < $length; $i ++) {
        $key .= $keys[mt_rand(0, count($keys) - 1)];
    }
    $randomString = $key;
    return $randomString;
}
echo "<br>Using mt_rand(): " . getRandomStringMtrand();
?>

6) Using hashing sha1()

It applies sha1 hash of the string which is the result of the rand().

Then, it extracts the substring from the hash with the specified length.

<?php
/**
 *
 * Using sha1().
 * sha1 has a 40 character limit and always lowercase characters.
 *
 * @param int $length
 * @return string
 */
function getRandomStringSha1($length = 16)
{
    $string = sha1(rand());
    $randomString = substr($string, 0, $length);
    return $randomString;
}
echo "<br>Using sha1(): " . getRandomStringSha1();
?>

7) Using hashing md5()

It applies md5() hash on the rand() result. Then, the rest of the process are same as the above example.

<?php
/**
 *
 * Using md5().
 *
 * @param int $length
 * @return string
 */
function getRandomStringMd5($length = 16)
{
    $string = md5(rand());
    $randomString = substr($string, 0, $length);
    return $randomString;
}
echo "<br>Using md5(): " . getRandomStringMd5();
?>

8) Using PHP uniqid()

The PHP unigid() function gets prefixed unique identifier based on the current time in microseconds.

It is not generating cryptographically random number like random_int() and random_bytes().

<?php
/**
 *
 * Using uniqid().
 *
 * @param int $length
 * @return string
 */
function getRandomStringUniqid($length = 16)
{
    $string = uniqid(rand());
    $randomString = substr($string, 0, $length);
    return $randomString;
}
echo "<br>Using uniqid(): " . getRandomStringUniqid();
?>

Download

Comments

Popular posts from this blog

IOT Projects souce code

IOT  Projects souce code What is IoT? The Internet of Things (IoT) is a network where everyday objects like devices, vehicles, and appliances have sensors and internet connectivity. It lets them gather and share data, work together, and perform tasks without human control. This helps boost automation and efficiency across different areas. You can learn IoT to understand its core components and get further knowledge of its functionalities. 20 IoT Projects with Source Code When it comes to IoT, there are many interesting ideas to explore, from making your home smarter to making an autonomous drone. No matter if you’re just starting or have experience, here are 20 Internet of things projects for beginners and advanced professionals. Simple IoT Project Ideas for Beginners For beginner-level, you can start with simple and fun IoT project ideas that involve basic components like sensors, actuators, and microcontrollers. Below are a few of them: 1. Smart Home Automation Smart home automat...

Connecting R to MySql in English #Training Trains

software design institute training

  ONLINE-OFFLINE IN-PLANT/INTERNSHIP With Certificate Training For B.E(ECE,EEE,CSE,IT,AI,ML,DataScience,Cyper Security),MCA, B.Sc,M.E,M.Tech. @ TrainingTrains.Online Classes Available 100 % Job placement Training Full Stack Developer | Placement Training In-plant Training/Internship Training with Project supports the various Engineering and Non-Engineering, Arts Students to develop their Skills on the IT Companies/Corporate Expectations. DURATION OF IN-PLANT TRAINING: 1 week and Above.DURATION OF INTERNSHIP: 1 Month and Above Internship-inplant training For All Departments students, Internship- inplant Training Python | Java | Full Stack Development | UI & UX | C& C++ | Php | Web Designing - HTML, CSS, Java Script, Bootstrap | MEAN Stack | MERN Stack | MEARNStack | Android | Kotlin | Flutter | Database - Oracle, Mongo DB, MySQL, MS SQL Serer | Visual Studio Code | Objective C | Swift | Go Lang | Frame work - Laravel, Django, Vue JS | Machine Learning | React JS | ...