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

Share:

How to Read a CSV to Array in PHP

 There are many ways to read a CSV file to an array. Online hosted tools provide interfaces to do this. Also, it is very easy to create a custom user interface for the purpose of reading CSV to the array.

In PHP, it has more than one native function to read CSV data.

  • fgetcsv() – It reads the CSV file pointer and reads the line in particular to the file handle.
  • str_getcsv() -It reads the input CSV string into an array.

This article provides alternate ways of reading a CSV file to a PHP array. Also, it shows how to prepare HTML from the array data of the input CSV.

Quick example

This example reads an input CSV file using the PHP fgetcsv() function. This function needs the file point to refer to the line to read the CSV row columns.

<?php

// PHP function to read CSV to array
function csvToArray($csv)
{
    // create file handle to read CSV file
    $csvToRead = fopen($csv, 'r');

    // read CSV file using comma as delimiter
    while (! feof($csvToRead)) {
        $csvArray[] = fgetcsv($csvToRead, 1000, ',');
    }

    fclose($csvToRead);
    return $csvArray;
}

// CSV file to read into an Array
$csvFile = 'csv-to-read.csv';
$csvArray = csvToArray($csvFile);

echo '<pre>';
print_r($csvArray);
echo '</pre>';
?>

This program sets the CSV file stream reference and other parameters to read the records in a loop.

The loop iteration pushes the line data into an array. The PHP array push happens using one of the methods we have seen in the linked article.

Save the below comma-separated values to a csv-to-array.csv file. It has to be created as an input of the above program.

csv-to-array.csv

Lion,7,Wild
Tiger,9,Wild
Dog,4,Domestic

Output:

The above program returns the following array after reading the input CSV file data.

Array
(
    [0] => Array
        (
            [0] => Lion
            [1] => 7
            [2] => Wild
        )

    [1] => Array
        (
            [0] => Tiger
            [1] => 9
            [2] => Wild
        )

    [2] => Array
        (
            [0] => Dog
            [1] => 4
            [2] => Domestic
        )

)

csv to PHP array

Map str_getcsv() to read CSV and convert it into a PHP array

This program will be suitable if you want to skip the step of writing a loop. It saves the developer’s effort. But the background processing will be the same as the above program.

The PHP file() converts the entire CSV into an array. Then, the array_map sets the str_getcsv() function as a callback to iterate the array of CSV file rows.

The str_getcsv() imports the CSV row data into an array. In a previous article, we have seen about handling CSV file read and other operations like import, and export.

The resultant $csvArray variable will contain the complete CSV data in a multi-dimensional array.

The output of this program will be similar to that of the quick example.

<?php
// a one-line simple option to reade CSV to array
// it uses PHP str_getcsv
$csvArray = array_map('str_getcsv', file('csv-to-read.csv'));
echo '<pre>';
print_r($csvArray);
echo '</pre>';
?>

Convert CSV to Array and then convert array to HTML

This example will be useful if you want to display the CSV content in the UI in a tabular form.

Mostly, this code must be more useful since it has the possibility of using it in real-time projects. But, the other examples are basics which are also important to learn about reading CSV using PHP.

This code iterates the CSV row and reads the column data using fgetcsv() as did in the quick example.

Then, it forms the HTML table structure using the CSV array data. In a previous tutorial, we saw code to convert an HTML table into an excel.

<?php

// PHP script to read CSV and convert to HTML table

// create file handle to read CSV file
$csvFile = fopen('csv-to-read.csv', 'r');

if ($csvFile !== FALSE) {
    echo "<table border=1 cellpadding=10>";
    while (($csvArray = fgetcsv($csvFile, 100, ',')) !== FALSE) {
        echo "<tr>";
        for ($i = 0; $i < count($csvArray); $i ++) {
            echo "<td>" . $csvArray[$i] . "</td>";
        }
        echo "</tr>";
    }
    echo "</table>";
    fclose($csvFile);
}
?>

Output:

This program will display the HTML table on the screen. The row data is from the input CSV file.

csv to html
Download

Share:

Live Chat With Us

My Blog List

Search This Blog

Locations

Training

Pages

My Blog List

Blog Archive

Privacy policy