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

PHP, at the time of its launch, stood for Personalized Home Page. And while its evolutionary journey gave the industry an alternate and more acceptable (recursive) definition as PHP: Hypertext PreProcessor, the truth about PHP is that it still imbibes the spirit of personalisation more than anything else. 

Today, PHP is the most preferred, free, and open-source alternative to all other leading server-configuration languages, such as Microsoft’s ASP (Active Server Pages). A large part of this personalization aspect is carried forward by the presence of a PHP interpreter at the server-side, which can be implemented either as a module, a daemon, or an executable.

PHP interfaces are helpful in the management of important user-centric data such as UIDs (Unique Identifiers), email addresses, usernames, passwords, confidential contact information, and much more.

Many, if not all, of the world’s leading dynamic content management systems (including the CMS giant WordPress), are PHP-based platforms that allow the easy creation and maintenance of both user records and content records, in the form of PHP-accessible databases.

In this article, we will explore one particular aspect of PHP that makes it so easy for administrators to populate all the mandatory fields needed in the act of creating a new “user” with minimum intervention from both the admin side as well as the user’s side. To do this, admins must learn how to generate PHP random strings, and that’s what we will cover.

Read: PHP Project Ideas & Topics

What is a PHP Random String?

A PHP Random String is a unique, randomised, and an alphanumeric string of characters that can be used in an array as a filename, as a random URL extension, as a password, or as an authentication token (such as the commonplace API Tokens and API Secrets as seen on Facebook’s app-development interface).

Frequent bloggers, especially those who use platforms such as Medium to publish their work, will see this act of random string generation in action whenever they publish a new story or post – the URL extension that follows the base domain, is usually the result of an arbitrary string being generated by the publishing interface. 

For instance, in the URL, the last part of the URL (c37d87e3386b) is a randomly generated string. Other easy and important references of PHP random strings include the “default” passwords that are generated for all new user accounts on WordPress.

An increasing majority of consumer internet platforms are also shifting towards the use of PHP random strings to leverage the power of encryption in enabling “magic link” sign-ins. If you have ever used a cloud-based service that uses a “magic link” sign in, you are already familiar with the ease, efficiency, and enhanced layer of security that is provided with the generation and mapping of PHP random strings.

How To Generate A PHP Random String?

The task at hand is to write code that generates random, alphanumeric, and unique strings using PHP. There are four different ways in which this can be achieved:

  1. By using brute force (random indexing) –This is by far the easiest, yet a crude method to achieve a PHP random string.
  2. By using “hashing” functions (algorithmic generation of PHP random strings – this is a little more intelligent approach as compared to using brute force)
  3. By using the in-built uniqid() function (this is straightforward and leverages an in-built PHP functionality to generate unique identifiers for elements)
  4. By using random_bytes() followed by bin2hex() – his generates cryptographically secure random bytes, and offers amazing functionality to interfaces such as online lotteries, online poker games and other platforms that require real-time number generation with true randomisation built into their core.

Also Read: Career Opportunities in PHP

Generating a PHP Random String using Brute Force

The brute force concept of random string generation in PHP is the simplest to understand and the easiest to implement. Broadly, the brute force approach can be explained in four easy steps:

  1. Club all possible characters and put them in one string (this is your sample space repository of all allowed characters in your string).
  2. Generate a “random index” that starts at 0 (zero) and extends to the string length “-1”.
  3. Print a character at the current index position.
  4. If X is the number of characters you need in your string (your desired string length), then repeat steps 1, 2 and 3 a total of X times in your total instruction loop.

As you can see in the sample code implementation below, this is by far the most straightforward way of generating a random string in PHP.

Sample Code:



function getName($n) { 

    $characters = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’; 

    $randomString = ”; 

    for ($i = 0; $i < $n; $i++) { 

        $index = rand(0, strlen($characters) – 1); 

        $randomString .= $characters[$index]; 



    return $randomString; 

 echo getName($n); 


Must Read: PHP Interview Questions & Answers

Generating a PHP Random String using “Hashing” functions

PHP has some in-built functions known as “hashing functions”, such as md5(), sha1() and hash(). These functions can be used to “hash” a string defined by specific algorithms such as “sha1”, “sha256”, and “md5”. In all of these functions, the argument is a string, and the output is an alphanumeric hashed string (As seen in the sample code below).

Sample Code:



$result = md5($str); 

echo $result; 


Generating a PHP Random String using the in-built “uniqid()” function

PHP retains a semblance of its value as a personalisation tool par excellence, with special in-built functions such as uniqid(), which can be used to generate a “Unique ID (UID)” that is derived from the current time, recorded in microseconds (also known as “micro time”).

Under default syntax, the uniqid() function always returns a unique alphanumeric string that has a string length of 13 characters. You can use the sample code below to test an implementation of the uniqid() method.

Sample Code:


$result = uniqid();   

echo $result; 


Generating a PHP Random String using random_bytes() and bin2hex() 

This, by far, is the most evolved and secure way of generating “pseudo-random ” bytes and then converting them into a hexadecimal format to add a layer of encryption to the existing randomisation.

The first step is to call the in-built random_bytes() function to generate cryptographically secure random bytes. The next step is to call the bin2hex() function that will use this binary data (number of bytes) as the argument and generate a corresponding hexadecimal value as output, which is a perfectly usable and unique alphanumeric string. This is better explained in the sample code below.

Sample Code:


$n = 20; 

$result = bin2hex(random_bytes($n)); 

echo $result; 


What Next?

upGrad brings programming with PHP and a lot more with upGrad’s PG Diploma in Software Development Specialisation in Full Stack Development. A program to make you emerge as a full stack developer and learning to build some of the awesome applications. It is an extensive 12-months program that includes working on live projects and assignments and also training 15 programming languages and tools. Along with it, it has all-time career support with mock interviews and job assistance.

Land on Your Dream Job

Learn More

Leave a comment

Your email address will not be published.

Accelerate Your Career with upGrad

Our Popular Software Engineering Courses