Random generated string in php

How to Generate a Random String with PHP

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

Using the Brute Force

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

  1. Storing all the possible letters into strings.
  2. Generating a random index from 0 to the length of the string -1 .
  3. Printing the letter on the given index.
  4. Implementing the steps n times ( n is considered the length of the required string).
 $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);

Applying Hashing Functions

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.
 $str = rand(); $result = md5($str); echo $result; ?>

The output will look like this:

2e437510c181dd2ae100fc1661a445d4

Applying the Uniqid() Function

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:

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

The first output is the following:

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.

Using Random_bytes() Function ( The Most Secured)

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.

 $n = 20; $result = bin2hex(random_bytes($n)); echo $result; ?>
235aed08a01468f90fa726bd56319fb893967da8
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 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.

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

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.

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.

$characters = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;

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

$randomString .= $characters[$index];

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).

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.

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.

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

Ads of upGrad blog

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.

Источник

Читайте также:  Открываться wp login php
Оцените статью