How To Generate A Random String In PHP [With Examples]

Guide to Generate a Random String In PHP – To begin, I’d want to point out that nearly no incident is actually random. Even the outcome of a traditional coin flip might be predicted in principle if we know the effects of all of the variables involved, such as air friction, gravity, and beginning force.

Random numbers and alphanumeric sequences can both be generate in the same way. The most we can hope for is to create random numbers and strings that don’t appear to follow a pattern and that an attacker couldn’t predict.

In this tutorial, we’ll look at how to generate random numbers and alphanumeric sequences in PHP using several strategies. Some will be cryptographically secure, while others, such as assigning pseudo-random file names, establishing URLs, and recommending usernames, will be purely for fun.

  • Random String Using Brute Force
  • Using Hashing Functions
  • Random String Using uniqid() function.
  • Using random_bytes() function. (Cryptographically Secure)

Approach 01: Random String In PHP Using Brute Force

The first approach is the most straightforward to understand, and so is brute force. It may be done in the following way:

  • Store all the possible letters into a string.
  • Generate random index from 0 to string length-1.
  • Print the letter at that index.
  • Perform this step n times (where n is the length of string required).

Example 01:

<?php
$n=10;
function getName($n) {
	$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$randomString = '';

	for ($i = 0; $i < $n; $i++) {
		$index = rand(0, strlen($characters) - 1);
		$randomString .= $characters[$index];
	}

	return $randomString;
}
echo "Hello from Softhunt.net";

echo getName($n);
?>

Output: After the first click

Random String In PHP using brute

Output: After the second click

Random String In PHP using brute

Approach 02: Random String In PHP Using Hashing Functions

PHP has methods such as md5(), sha1(), and hash() that may be used to hash a text using algorithms such as “sha1”, “sha256”, “md5”, and so on. These functions all accept a string as input and return an Alpha-Numeric hashed string.

Our work becomes quite straightforward if we understand how to use these functions.

  • Generate a random number using rand() function.
  • Hash it using one of the above functions.

Example 02:

<?php
$str=rand();
$result = md5($str);
echo "Hello from Softhunt.net";

echo $result;
?>

Output: After the first click

Random String In PHP using hashing

Output: After the second click

Random String In PHP using hashing

Example 03:

<?php
$str=rand();
$result = sha1($str);
echo "Hello from Softhunt.net";

echo $result;
?>

Output: After the first click

Random String In PHP using hashing

Output: After the second click

Random String In PHP using hashing

Example 04:

<?php
$str = rand();
$result = hash("sha256", $str);
echo "Hello from Softhunt.net";

echo $result;
?>

Output: After the first click

Random String In PHP using hashing

Output: After the second click

Random String In PHP using hashing

Note: Because all of the above functions are hashing functions, the length of the string created will always depend on the method employed, but it will always be constant for an algorithm. So, if you want to construct a string of a specific length, you may either truncate it or concatenate it with another string, depending on your needs.

Approach 03:Using uniqid() function

The PHP uniqid() function is a built-in function that generates a unique ID based on the current time in microseconds (micro time). It returns a 13-character unique string by default.

Example 05:

<?php 
$result = uniqid(); 
echo "Hello from Softhunt.net";

echo $result;
?> 

Output: After the first click

using unique id

Output: After the second click

using unique id

Note: All of the above methods rely on the rand() and uniqid() functions. These functions do not generate random numbers in a cryptographically safe manner. As a result, if the degree of randomness has an impact on an application’s security, these approaches should be avoided.

Approach 04: Using random_bytes() function. (Cryptographically Secure)

The random_bytes() method creates cryptographically safe pseudo-random bytes that may be converted to hexadecimal using the bin2hex() function.

Example 06:

<?php 
$n = 20;
$result = bin2hex(random_bytes($n));
echo "Hello from Softhunt.net";

echo $result;
?> 

Output: After the first click

using random byte

Output: After the second click

using random byte

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn.

Suggested Articles:

  1. Random Code Generator JavaScript

Leave a Comment