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.

Check out our free courses to get an edge over the competition.

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. 

Check out upGrad’s Advanced Certification in Cyber Security 

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.

Explore our Popular Software Engineering Courses

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.

Check out upGrad’s Advanced Certification in Cloud Computing 

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; 


In-Demand Software Development Skills

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; 


Explore Our Software Development Free Courses

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.

How can I learn both front-end and back-end development?

Front-end development is the process of establishing a website's or application's user interface (UI) and interactivity. This covers the items on the screen's layout, font, color, and motion. To produce a functioning and appealing interface, front-end developers use a number of technologies such as HTML, CSS, and JavaScript. The process of developing the functionality and features of a website or application is known as back-end development. This comprises the design and architecture of the back-end systems, as well as the coding and programming of the website or application. Back-end developers collaborate with front-end developers to build a fully functional website or app. If you're beginning from scratch, front-end development can be a good place to start. This will offer you an overview of how the web works and how to make static sites. You can move on to learning back-end development once you have a solid understanding of front-end development.

What are some good web designing tools?

Adobe Photoshop, Adobe Dreamweaver, and Adobe Illustrator are all excellent web design tools. Adobe Photoshop is a piece of software that lets you create and modify photos. It's used for everything from simple logo design to photo retouching. Layers, filters, and masks are just a few of the features that allow you to build intricate patterns. Adobe Dreamweaver is a piece of software that lets you build and edit websites. It offers tools for creating and editing HTML, CSS, and JavaScript code. It also includes a preview option that lets you see how your website will look on various devices.

What is the alternative to HyperText?

HyperText is content that has been arranged in such a way that the reader can easily travel between different sections. HyperText can be used to construct links between portions of a text, allowing the reader to jump between them with a single click. A text-based system is an alternative to hypertext in which the user can only go forward or backward through the text and cannot hop to other portions of the text.

Want to share this article?

Land on Your Dream Job

Learn More

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks