Random Strings

Creating a random alphanumeric string (numbers and letters) in PHP is often a necessity, and is very easy to achieve. This article shows you how in just one short line of code!

The are often times when you might want to create a random string consisting
of only letters and numbers in PHP, the great example that springs to mind
in passwords or validation codes. Doing so is easy for any length of string
thanks to a few simple PHP functions.

First of all, and with one simple line, lets look at how to create a
random string that's 32 characters long:

<?php
echo md5(microtime());
?>

This example creates a random 32 character string. The md5 function
(PHP: md5())
returns a 32 character long hexdecimal encoded form of the variable
passed to it's md5 hash (a secure method for mathematically identifying
strings). The variable we pass to it is the return value of the
microtime function
(PHP: microtime())
which returns the number of seconds and microseconds (millionths of a
second) that have elapsed since the Unix epoch (January 1st, 1970).
Due to the constant variation in the return value of microtime,
the strings generated are very variable.

Variable length random strings

Sometimes of course, you may want to create random strings of a
different length. If you use this method to create random passwords,
and always create random passwords 10 characters in length, it's going
to make life easier for would-be hackers. To create passwords of
varying length we can incorperate the substr and rand
functions.

To make a random string of between eight and 18 characters, we could
do the following:

<?php
echo substr(md5(microtime()), 0, rand(8, 18));
?>

Longer random strings

Should you need to create longer random strings (more than 32 characters),
this function will allow you to specify a minimum and maximum string
length, and a random string with a length between the minimum and
maximum you specify: