How to generate random codes in php?

Last update on August 19 2022 21:50:29 (UTC/GMT +8 hours)

PHP String: Exercise-9 with Solution

Write a PHP script to generate simple random password [do not use rand() function] from a given string.

Sample string : '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz'
Note : Password length may be 6, 7, 8 etc.

Sample Solution:

PHP Code:

<?php
function password_generate($chars) 
{
  $data = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz';
  return substr(str_shuffle($data), 0, $chars);
}
  echo password_generate(7)."\n";
?>

Sample Output:

89Qp3AK

Flowchart :

How to generate random codes in php?

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP script to format values in currency style.
Next: Write a PHP script to replace the first 'the' of the following string with 'That'.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

PHP: Tips of the Day

PHP: How to remove non-alphanumeric characters?

Sounds like you almost knew what you wanted to do already, you basically defined it as a regex.

preg_replace("/[^A-Za-z0-9 ]/", '', $string);

Ref : https://bit.ly/35TkbcF


  • Exercises: Weekly Top 16 Most Popular Topics
  • SQL Exercises, Practice, Solution - JOINS
  • SQL Exercises, Practice, Solution - SUBQUERIES
  • JavaScript basic - Exercises, Practice, Solution
  • Java Array: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : Conditional Statement
  • HR Database - SORT FILTER: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : String
  • Python Data Types: Dictionary - Exercises, Practice, Solution
  • Python Programming Puzzles - Exercises, Practice, Solution
  • C++ Array: Exercises, Practice, Solution
  • JavaScript conditional statements and loops - Exercises, Practice, Solution
  • C# Sharp Basic Algorithm: Exercises, Practice, Solution
  • Python Lambda - Exercises, Practice, Solution
  • Python Pandas DataFrame: Exercises, Practice, Solution
  • Conversion Tools
  • JavaScript: HTML Form Validation


How to generate random codes in php?

Published January 20, 2020 by

To generate random alphanumeric string there are many ways to generate a random, unique, alphanumeric string in PHP. The following ways to generate random alphanumeric string

Using str_shuffle() Function: 

The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter. When a number is passed, it treats the number as the string and shuffles it. This function does not make any change in the original string or the number passed to it as a parameter. Instead, it returns a new string which is one of the possible permutations of the string passed to it in the parameter.

Example

$length = 10;
$data = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz';

echo substr(str_shuffle($used_symbols), 0, $length);
echo "<br />";
echo substr(str_shuffle($used_symbols), 0, 8);

Output

2 y fd5eIFrh
ujwRe9k2

Using md5() Function:

The md5() function is used to calculate the MD5 hash of a string. Pass timestamp as a argument and md5 function will convert them into 32 bit characters

echo substr(md5(microtime()), 0, 10); 
echo substr(md5(microtime()), 0, 8); 

// output
3b8d94d66f
e73741a368

  • PHP generate random number using rand() / mt_rand() function
  • Learn about PHP Date and time function
  • Sending Email in PHP

In the framework of this snippet, we will explain several ways of generating a unique, random string with the help of PHP arsenal.

The first way is using the brute force. It is the simplest method that can be achieved by following the steps below:

  • Storing all the possible letters into strings.
  • Generating a random index from 0 to the length of the string -1.
  • Printing the letter on the given index.
  • Implementing the steps n times (n is considered the length of the required string).
  • Here is an example:

    <?php
    $n=10;
    function getRandomString($n) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
      
        for ($i = 0; $i < $n; $i++) {
            $index = rand(0, strlen($characters) - 1);
            $randomString .= $characters[$index];
        }
      
        return $randomString;
    }
      
    echo getRandomString($n);

    Here is the first output:

    And, the second one:

    In PHP, there are several functions such as md5(), sha1(), and hash() that might be applied for hashing a string based on exact algorithms such as “sha1”, “sha256”, “md5”, and so on.

    All of these functions are capable of taking a string as an argument and output an Alpha-Numeric hashed string.

    After understanding how to utilize the functions, the next steps become simpler:

    1. Generating a random number with the rand() function.
    2. Hashing it with one of the functions above.

    Here is an example:

    <?php
    $str=rand();
    $result = md5($str);
    echo $result;
    ?>

    The output will look like this:

    2e437510c181dd2ae100fc1661a445d4

    This is an inbuilt function that is applied for generating a unique ID built on the current time in microseconds. It returns a 13-character long unique string, by default.

    The example is demonstrated below:

    <?php 
    $result = uniqid();  
    echo $result;
    ?>

    The first output is the following:

    Here is the second one:

    Please, take into consideration that all the methods above are based on rand() and uniqid() functions. However, they are not considered cryptographically secure random generators.

    If you want to generate cryptographically secure pseudo random bytes that can be converted into a hexadecimal format with the bin2hex() function, then you should use the random_bytes function.

    Here is an example:

    <?php 
    $n = 20;
    $result = bin2hex(random_bytes($n));
    echo $result;
    ?>

    Here is the first output:

    235aed08a01468f90fa726bd56319fb893967da8

    The second one:

    508b84494cdf31bec01566d12a924c75d4baed39

    So, in this snippet, we represented several ways to generate a random string with PHP. Learning them will make your work easier and more productive.

    How can I generate 5 random numbers in PHP?

    rand() or mt_rand() functions can be used to Generate 5 Digit Random Number in PHP.

    How do I generate a random 10 digit number in PHP?

    rand() or mt_rand() functions can be used to Generate 10 Digit Random Number in PHP.

    How can I generate random alphanumeric code in PHP?

    If you want to generate random alphanumeric strings from a fixed set of characters, you can use the str_shuffle($string) function. This function will provide you a randomly shuffled string.

    How do I generate a random 4 digit number in PHP?

    rand() or mt_rand() functions can be used to Generate 4 Digit Random Number in PHP.