Posts tagged ‘random alphanumeric string’

In order to generate a random string of letters and numbers we will be merging together two php functions. If you want to limit it’s size or limit it to just letters we will also be going over such topics.
Please look over the following functions before we begin:
1. The mt_rand function which generates a random number similarly to rand but 4x faster.
2. The sha1 function which generates a random 32character string of letters and numbers.
3. The substr function which cuts a word by a select number of letters.
4. The str_replace function which replaces a select letter/word/symbol.
5. Arrays and functions as they will be used to commit an str_replace.

Begin Tutorial————————–

1. Start with adding a number 0-999 or higher if you choose:

<?
$rand = mt_rand(0,999);
?>

2. Then create a random sha1 hash code:

<?
$rand = mt_rand(0,999);
$hash = sha1($rand);
echo"".$hash."";
?>

3. You now have a 32character string but what if you wanted a 10 character string? Well here’s how using substr:

<?
$rand = mt_rand(0,999);
$hash = sha1($rand);
$first10 = substr($hash, 0, 9);
echo"".$first10."";
?>

4. But what if you wanted just the first 10 letters? Use str_replace in a function:

<?
function remove_numbers($string) {
$numbers = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", " ");
$string = str_replace($numbers, '', $string);
$string = substr($string, 0, 9);
return $string;
}
$rand = mt_rand(0,999);
$hash = sha1($rand);
echo remove_numbers($hash);
?>

5. What if you wanted it to be a very long string? Of course you could merge hashes together, but then that is just extra work. Let’s take another approach using strlen we will loop through a list of numbers and letters 10 times as defined by $length. To limit it to letters just delete the numbers in $characters.

<?
function RandomString() {
    $length = 10;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string = '';    
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}
echo RandomString();
?>

6. We can even pass the amount of characters through as a function like so (this will create a random 20 character string):

<?
function RandomString($length) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string = '';    
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}
echo RandomString(5);
?>