Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconHow To Generate A Random String In PHP [With Examples]

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

Last updated:
24th Nov, 2020
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
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.

Ads of upGrad blog

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 https://medium.com/neli/shiring-revealing-the-best-kept-secret-of-ancient-indian-meditation-c37d87e3386b, 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:

<?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 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:

<?php 

$str=rand(); 

$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:

<?php  

$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:

<?php  

$n = 20; 

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

Ads of upGrad blog

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.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1How 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.

2What 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.

3What 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.

Explore Free Courses

Suggested Blogs

Full Stack Developer Salary in India in 2024 [For Freshers &#038; Experienced]
907174
Wondering what is the range of Full Stack Developer salary in India? Choosing a career in the tech sector can be tricky. You wouldn’t want to choose
Read More

by Rohan Vats

15 Jul 2024

SQL Developer Salary in India 2024 [For Freshers &#038; Experienced]
902298
They use high-traffic websites for banks and IRCTC without realizing that thousands of queries raised simultaneously from different locations are hand
Read More

by Rohan Vats

15 Jul 2024

Library Management System Project in Java [Comprehensive Guide]
46958
Library Management Systems are a great way to monitor books, add them, update information in it, search for the suitable one, issue it, and return it
Read More

by Rohan Vats

15 Jul 2024

Bitwise Operators in C [With Coding Examples]
51783
Introduction Operators are essential components of every programming language. They are the symbols that are used to achieve certain logical, mathema
Read More

by Rohan Vats

15 Jul 2024

ReactJS Developer Salary in India in 2024 [For Freshers &#038; Experienced]
902675
Hey! So you want to become a React.JS Developer?  The world has seen an enormous rise in the growth of frontend web technologies, which includes web a
Read More

by Rohan Vats

15 Jul 2024

Password Validation in JavaScript [Step by Step Setup Explained]
48976
Any website that supports authentication and authorization always asks for a username and password through login. If not so, the user needs to registe
Read More

by Rohan Vats

13 Jul 2024

Memory Allocation in Java: Everything You Need To Know in 2024-25
74112
Starting with Java development, it’s essential to understand memory allocation in Java for optimizing application performance and ensuring effic
Read More

by Rohan Vats

12 Jul 2024

Selenium Projects with Eclipse Samples in 2024
43495
Selenium is among the prominent technologies in the automation section of web testing. By using Selenium properly, you can make your testing process q
Read More

by Rohan Vats

10 Jul 2024

Top 10 Skills to Become a Full-Stack Developer in 2024
230001
In the modern world, if we talk about professional versatility, there’s no one better than a Full Stack Developer to represent the term “versatile.” W
Read More

by Rohan Vats

10 Jul 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon