10-06-2022, 04:07 PM
How to Generate PHP Random String Token (8 Ways)
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/10/how-to-generate-php-random-string-token-8-ways.jpg" width="513" height="313" title="" alt="" /></div><div><div class="modified-on" readability="7.1111111111111"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on October 5th, 2022.</div>
<p>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.</p>
<p>I present eight different ways of getting a random string token using PHP.</p>
<ol>
<li>Using <em>random_int()</em></li>
<li>Using <em>rand()</em></li>
<li>By string shuffling to generate a random substring.</li>
<li>Using <em>bin2hex()</em></li>
<li>Using <em>mt_rand()</em></li>
<li>Using hashing <em>sha1()</em></li>
<li>Using hashing <em>md5()</em></li>
<li>Using PHP <em>uniqid()</em></li>
</ol>
<p>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.</p>
<h2>1) Using <em>random_int()</em></h2>
<p>The PHP <em>random_int()</em> function generates cryptographic pseudo random integer. This random integer is used as an index to get the character from the given string base.</p>
<p>The string base includes 0-9, a-z and A-Z characters to return an alphanumeric random number.</p>
<div class="post-section-highlight" readability="38">
<h3>Quick example</h3>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
</div>
<p><img loading="lazy" class="alignnone size-full wp-image-19678" src="https://phppot.com/wp-content/uploads/2022/10/php-random-string.jpg" alt="php random string" width="513" height="313" srcset="https://phppot.com/wp-content/uploads/2022/10/php-random-string.jpg 513w, https://phppot.com/wp-content/uploads/20...00x183.jpg 300w" sizes="(max-width: 513px) 100vw, 513px"></p>
<h2>2) Using <em>rand()</em></h2>
<p>It uses simple PHP <em>rand()</em> and follows straightforward logic without encoding or encrypting.</p>
<p>It calculates the given string base’s length and pass it as a limit to the <em>rand()</em> function.</p>
<p>It gets the random character with the random index returned by the <em>rand()</em>. It applies string concatenation every time to form the random string in a loop.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<h2>3) By string shuffling to generate a random substring.</h2>
<p>It returns the random integer with the specified length.</p>
<p>It applies PHP string repeat and shuffle the output string. Then, extracts the substring from the shuffled string with the specified length.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<h2>4) Using <em>bin2hex()</em></h2>
<p>Like <em>random_int()</em>, the <em>random_bytes()</em> returns cryptographically secured random bytes.</p>
<p>If the function doesn’t exists, this program then uses <em>openssl_random_pseudo_bytes()</em> function.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<h2>5) Using <em>mt_rand()</em></h2>
<p>PHP <em>mt_rand() </em>is the replacement of <em>rand().</em> It generates a random string using the Mersenne Twister Random Number Generator.</p>
<p>This code generates the string base dynamically using the <em>range()</em> function.</p>
<p>Then, it runs the loop to build the random string using <em>mt_rand()</em> in each iteration.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<h2>6) Using hashing <em>sha1()</em></h2>
<p>It applies sha1 hash of the string which is the result of the <em>rand()</em>.</p>
<p>Then, it extracts the substring from the hash with the specified length.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<h2>7) Using hashing <em>md5()</em></h2>
<p>It applies <em>md5()</em> hash on the <em>rand() </em>result. Then, the rest of the process are same as the above example.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<h2>8) Using PHP <em>uniqid()</em></h2>
<p>The PHP <em>unigid()</em> function gets prefixed unique identifier based on the current time in microseconds.</p>
<p>It is not generating cryptographically random number like <em>random_int()</em> and <em>random_bytes()</em>.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<p><a class="download" href="https://phppot.com/downloads/php/php-random-string.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/php-random-string/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2022/10/...en-8-ways/
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/10/how-to-generate-php-random-string-token-8-ways.jpg" width="513" height="313" title="" alt="" /></div><div><div class="modified-on" readability="7.1111111111111"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on October 5th, 2022.</div>
<p>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.</p>
<p>I present eight different ways of getting a random string token using PHP.</p>
<ol>
<li>Using <em>random_int()</em></li>
<li>Using <em>rand()</em></li>
<li>By string shuffling to generate a random substring.</li>
<li>Using <em>bin2hex()</em></li>
<li>Using <em>mt_rand()</em></li>
<li>Using hashing <em>sha1()</em></li>
<li>Using hashing <em>md5()</em></li>
<li>Using PHP <em>uniqid()</em></li>
</ol>
<p>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.</p>
<h2>1) Using <em>random_int()</em></h2>
<p>The PHP <em>random_int()</em> function generates cryptographic pseudo random integer. This random integer is used as an index to get the character from the given string base.</p>
<p>The string base includes 0-9, a-z and A-Z characters to return an alphanumeric random number.</p>
<div class="post-section-highlight" readability="38">
<h3>Quick example</h3>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
</div>
<p><img loading="lazy" class="alignnone size-full wp-image-19678" src="https://phppot.com/wp-content/uploads/2022/10/php-random-string.jpg" alt="php random string" width="513" height="313" srcset="https://phppot.com/wp-content/uploads/2022/10/php-random-string.jpg 513w, https://phppot.com/wp-content/uploads/20...00x183.jpg 300w" sizes="(max-width: 513px) 100vw, 513px"></p>
<h2>2) Using <em>rand()</em></h2>
<p>It uses simple PHP <em>rand()</em> and follows straightforward logic without encoding or encrypting.</p>
<p>It calculates the given string base’s length and pass it as a limit to the <em>rand()</em> function.</p>
<p>It gets the random character with the random index returned by the <em>rand()</em>. It applies string concatenation every time to form the random string in a loop.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<h2>3) By string shuffling to generate a random substring.</h2>
<p>It returns the random integer with the specified length.</p>
<p>It applies PHP string repeat and shuffle the output string. Then, extracts the substring from the shuffled string with the specified length.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<h2>4) Using <em>bin2hex()</em></h2>
<p>Like <em>random_int()</em>, the <em>random_bytes()</em> returns cryptographically secured random bytes.</p>
<p>If the function doesn’t exists, this program then uses <em>openssl_random_pseudo_bytes()</em> function.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<h2>5) Using <em>mt_rand()</em></h2>
<p>PHP <em>mt_rand() </em>is the replacement of <em>rand().</em> It generates a random string using the Mersenne Twister Random Number Generator.</p>
<p>This code generates the string base dynamically using the <em>range()</em> function.</p>
<p>Then, it runs the loop to build the random string using <em>mt_rand()</em> in each iteration.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<h2>6) Using hashing <em>sha1()</em></h2>
<p>It applies sha1 hash of the string which is the result of the <em>rand()</em>.</p>
<p>Then, it extracts the substring from the hash with the specified length.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<h2>7) Using hashing <em>md5()</em></h2>
<p>It applies <em>md5()</em> hash on the <em>rand() </em>result. Then, the rest of the process are same as the above example.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<h2>8) Using PHP <em>uniqid()</em></h2>
<p>The PHP <em>unigid()</em> function gets prefixed unique identifier based on the current time in microseconds.</p>
<p>It is not generating cryptographically random number like <em>random_int()</em> and <em>random_bytes()</em>.</p>
<pre class="prettyprint"><code class="language-php"><?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();
?>
</code></pre>
<p><a class="download" href="https://phppot.com/downloads/php/php-random-string.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/php-random-string/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2022/10/...en-8-ways/