Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

NetTuts.com:
Generate Random Alphanumeric Strings in PHP
Nov 21, 2018 @ 11:52:17

On the NetTuts.com site they've posted a tutorial showing how to generate random alphanumeric strings in PHP including information on how the different "randomness" methods work in PHP (and when to use which method).

Let me begin this post by saying that almost no event is truly random. Even the outcome of a classic coin toss could in theory be predicted if we knew the effect of every factor involved, like air friction, gravity, and initial force.

The same thing is applicable to the generation of random numbers and alphanumeric strings. The best we can hope for is to generate numbers and strings that don't seem to follow a pattern and can't be practically predicted by an attacker.

In this tutorial, we will cover different techniques for generating random numbers and alphanumeric strings in PHP. Some of them will be cryptographically secure, while others are meant only for casual use, like assigning pseudo-random file names or creating URLs and suggesting usernames.

They start with a look at generating random numbers using the rand, mt_rand and random_int functions. There's a mention of which to use when cryptographically secure random integers are needed as well. They also talk about seeding the random number generator and generating random float values.

From there they move on to the focus of the article - generating the random alphanumeric strings using a few different methods:

  • generating "shuffled" strings
  • generating random strings
  • generate random hexadecimal strings
  • generating cryptographically secure random strings

Each of the above sections (as well as the previous ones) come with code examples and explanations of the randomness each provides.

tagged: generate random alphanumeric strings tutorial cryptography

Link: https://code.tutsplus.com/tutorials/generate-random-alphanumeric-strings-in-php--cms-32132