8 Ways to Generate Random String in PHP Tutorial

Introduction

In this tutorial, you will learn the 8 Different Ways of Generating Random Strings using PHP Language. The tutorial aims to provide a reference or guide to the IT/CS students or new to PHP Language for using some of the built-in methods or functions of PHP. Here, snippets will be provided and a sample web program source code file is free to download.

Why Generate Random Strings?

In some cases, developers commonly generate random strings to create API Keys, Access Tokens, or Secret Keys for some features of the web applications. The main purpose of the said generated string is often used for security purposes for accessing some data on the server. Generating a random sting can be used for generating a unique random string.

Technologies

In this tutorial, we will use the following technologies:

  • Latest XAMPP with PHP Version 7.4+
  • Text Editors such as Sublime Text, Notepad++, or VS Code
  • HTML
  • CSS
  • Bootstrap (for interface design purposes)

8 ways of Generating Random Strings

Using md5()

The PHP md5() is a function that calculates the MD5 hash of a string. This function requires a string to convert into a hash.

Here is a sample snippet of generating a random string using md5().

  1. <?php
  2. function gen_using_md5($length = 16){
  3.     $code = md5(mt_rand(0, mt_getrandmax()));
  4.     $code = substr($code, 0, $length - 1);
  5.     return $code;
  6. }
  7. ?>

Using sha1()

The PHP sha1() is like an md5() that calculates the hash of strings. This hashing method calculates the hash of the string using the US Secure Hash Algorithm 1.

Here is a sample snippet of generating a random string using sha1().

  1. <?php
  2. function gen_using_sha1($length = 16){
  3.     $code = sha1(mt_rand(0, mt_getrandmax()));
  4.     $code = substr($code, 0, $length - 1);
  5.     return $code;
  6. }
  7. ?>

Using mt_rand()

The PHP mt_rand() function is a Random Number Generator using Mersenne Twister. Using this function we can generate a random number and select from a character in an array of characters.

Here is a sample snippet of generating a random string using mt_rand().

  1. <?php
  2. function gen_using_mt_rand($length = 16){
  3.     $strings = array_merge( range(0,9), range('a','z') );
  4.     $code = [];
  5.      for($i = 0 ;$i < $length ;$i++){
  6.         $code[] = $strings[mt_rand(0, count($strings) - 1)];
  7.      }
  8.     $code = implode('', $code);
  9.     return $code;
  10. }
  11. ?>

Using random_int()

The PHP random_int() function generates a cryptographically secure, informally selected integer.

Here is a sample snippet of generating a random string using random_int().

  1. <?php
  2. function gen_using_random_int($length = 16){
  3.     $strings = array_merge( range(0,9), range('a','z') );
  4.     $code = [];
  5.      for($i = 0 ;$i < $length ;$i++){
  6.         $code[] = $strings[random_int(0, count($strings) - 1)];
  7.      }
  8.     $code = implode('', $code);
  9.     return $code;
  10. }
  11. ?>

Using rand()

The PHP rand() function generates a random integer.

Here is a sample snippet of generating a random string using rand().

  1. <?php
  2. function gen_using_rand($length = 16){
  3.     $strings = array_merge( range(0,9), range('a','z') );
  4.     $code = [];
  5.      for($i = 0 ;$i < $length ;$i++){
  6.         $code[] = $strings[rand(0, count($strings) - 1)];
  7.      }
  8.     $code = implode('', $code);
  9.     return $code;
  10. }
  11. ?>

Using shuffle()

The PHP shuffle() function shuffles the order of an array. Using this and an array of characters, we can generate random strings.

Here is a sample snippet of generating a random string using shuffle().

  1. <?php
  2. function gen_using_shuffle($length = 16){
  3.     $strings = array_merge( range(0,9), range('a','z') );
  4.     shuffle($strings);
  5.     $strings = implode("", $strings);
  6.     $code = substr($strings, 0, $length);
  7.     return $code;
  8. }
  9. ?>

Using uniqid()

The PHP uniqid() function generates a unique ID. You can also add a string prefix for generating an ID.

Here is a sample snippet of generating a random string using uniqid().

  1. <?php
  2. function gen_using_uniqid($length = 16){
  3.     $code = uniqid(rand(), true);
  4.     $code = substr($code, 0, $length);
  5.     return $code;
  6. }
  7. ?>

Using bin2hex()

The PHP bin2hex() function converts binary data into hexadecimal representation. This function can generate random strings by converting random bytes using random_bytes().

Here is a sample snippet of generating a random string using bin2hex().

  1. <?php
  2. function gen_using_bin2hex($length = 16){
  3.     $code = bin2hex(random_bytes($length));
  4.     $code = substr($code, 0, $length);
  5.     return $code;
  6. }
  7. ?>

Example

Here's an example source code that demonstrates the 8 Different ways of Generating Random Strings.

Interface

  1. <?php require_once('functions.php') ?>
  2. <!DOCTYPE html>
  3. <html lang="en">
  4.     <meta charset="UTF-8">
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7.     <title>Generate Random String</title>
  8.  
  9.  
  10.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  11.     <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  12.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  13.  
  14.     <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  15.     <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
  16.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
  17.  
  18.     <style>
  19.         html, body{
  20.             min-height:100%;
  21.             width:100%;
  22.         }
  23.     </style>
  24. </head>
  25.     <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  26.         <div class="container">
  27.             <a class="navbar-brand" href="./">8 ways of Generate Random String</a>
  28.             <div>
  29.                 <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  30.             </div>
  31.         </div>
  32.     </nav>
  33.     <div class="container px-5 my-3">
  34.         <h2 class="text-center">8 ways of Generate Random String in PHP</h2>
  35.             <div class="col-lg-6 col-md-8 col-sm-12 mb-4 mx-auto">
  36.                 <div class="card shadow rounded-0">
  37.                     <div class="card-header rounded-0">
  38.                         <div class="d-flex justify-content-between">
  39.                             <div class="card-title flex-shrink-1 flex-grow-1">Generated </div>
  40.                             <div class="col-auto">
  41.                                 <button class="btn btn-primary btn-sm rounded-0" type="button" onclick="location.reload()">Generate Random</button>
  42.                             </div>
  43.                         </div>
  44.                     </div>
  45.                     <div class="card-body">
  46.                         <div class="container-fluid">
  47.                             <table class="table table-bordered table-striped">
  48.                                 <thead>
  49.                                     <tr>
  50.                                         <th>Use for Generating</th>
  51.                                         <th>Result</th>
  52.                                     </tr>
  53.                                 </thead>
  54.                                 <tbody>
  55.                                     <tr>
  56.                                         <td class="">md5()</td>
  57.                                         <td class=""><?= gen_using_md5() ?></td>
  58.                                     </tr>
  59.                                     <tr>
  60.                                         <td class="">sha1()</td>
  61.                                         <td class=""><?= gen_using_sha1() ?></td>
  62.                                     </tr>
  63.                                     <tr>
  64.                                         <td class="">mt_rand()</td>
  65.                                         <td class=""><?= gen_using_mt_rand() ?></td>
  66.                                     </tr>
  67.                                     <tr>
  68.                                         <td class="">random_int()</td>
  69.                                         <td class=""><?= gen_using_random_int() ?></td>
  70.                                     </tr>
  71.                                     <tr>
  72.                                         <td class="">rand()</td>
  73.                                         <td class=""><?= gen_using_rand() ?></td>
  74.                                     </tr>
  75.                                     <tr>
  76.                                         <td class="">shuffle()</td>
  77.                                         <td class=""><?= gen_using_shuffle() ?></td>
  78.                                     </tr>
  79.                                     <tr>
  80.                                         <td class="">uniqid()</td>
  81.                                         <td class=""><?= gen_using_uniqid() ?></td>
  82.                                     </tr>
  83.                                     <tr>
  84.                                         <td class="">bin2hex()</td>
  85.                                         <td class=""><?= gen_using_bin2hex() ?></td>
  86.                                     </tr>
  87.                                 </tbody>
  88.                             </table>
  89.                         </div>
  90.                     </div>
  91.                 </div>
  92.             </div>
  93.     </div>
  94. </body>
  95. </html>

PHP Scripts

  1. <?php
  2.  
  3. function gen_using_md5($length = 16){
  4.     $code = md5(mt_rand(0, mt_getrandmax()));
  5.     $code = substr($code, 0, $length - 1);
  6.     return $code;
  7. }
  8.  
  9.  
  10. function gen_using_sha1($length = 16){
  11.     $code = sha1(mt_rand(0, mt_getrandmax()));
  12.     $code = substr($code, 0, $length - 1);
  13.     return $code;
  14. }
  15.  
  16. function gen_using_mt_rand($length = 16){
  17.     $strings = array_merge( range(0,9), range('a','z') );
  18.     $code = [];
  19.         for($i = 0 ;$i < $length ;$i++){
  20.         $code[] = $strings[mt_rand(0, count($strings) - 1)];
  21.         }
  22.     $code = implode('', $code);
  23.     return $code;
  24. }
  25. function gen_using_random_int($length = 16){
  26.     $strings = array_merge( range(0,9), range('a','z') );
  27.     $code = [];
  28.         for($i = 0 ;$i < $length ;$i++){
  29.         $code[] = $strings[random_int(0, count($strings) - 1)];
  30.         }
  31.     $code = implode('', $code);
  32.     return $code;
  33. }
  34. function gen_using_rand($length = 16){
  35.     $strings = array_merge( range(0,9), range('a','z') );
  36.     $code = [];
  37.         for($i = 0 ;$i < $length ;$i++){
  38.         $code[] = $strings[rand(0, count($strings) - 1)];
  39.         }
  40.     $code = implode('', $code);
  41.     return $code;
  42. }
  43.  
  44. function gen_using_shuffle($length = 16){
  45.     $strings = array_merge( range(0,9), range('a','z') );
  46.     shuffle($strings);
  47.     $strings = implode("", $strings);
  48.     $code = substr($strings, 0, $length);
  49.     return $code;
  50. }
  51. function gen_using_uniqid($length = 16){
  52.     $code = uniqid(rand(), true);
  53.     $code = substr($code, 0, $length);
  54.     return $code;
  55. }
  56. function gen_using_bin2hex($length = 16){
  57.     $code = bin2hex(random_bytes($length));
  58.     $code = substr($code, 0, $length);
  59.     return $code;
  60. }
  61. ?>

That's it! You can test the sample program on your end and see if it meets our main goal for this tutorial. I have provided also the complete source code file that I created for this tutorial. You can download it by clicking the download button located below this article.

DEMO VIDEO

That's the end of this tutorial. I hope this 8 Ways of Generating Random String in PHP Tutorial will help you with what you are looking for and that you'll find this useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Enjoy :)

Add new comment