Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Random Serial with PHP

Tags:

php

I want to have a random serial created on my website everytime someone visits.

The format of the serial should be XXXXX-XXXXX-XXXXX-XXXXX.

X represents a random number or capital letter.


Unfortunately I have no idea how to do this. Could anybody please help me out?

So for example the random serial output could be: 3WT4A-NB34O-JU87P-B3UHS


Thanks a lot!

like image 292
Kid Diamond Avatar asked May 01 '12 17:05

Kid Diamond


2 Answers

Another approach is to calculate the four segments as random numbers in base 36.

function generate_serial() {
    static $max = 60466175; // ZZZZZZ in decimal
    return strtoupper(sprintf(
        "%05s-%05s-%05s-%05s",
        base_convert(random_int(0, $max), 10, 36),
        base_convert(random_int(0, $max), 10, 36),
        base_convert(random_int(0, $max), 10, 36),
        base_convert(random_int(0, $max), 10, 36)
    ));
}
like image 177
salathe Avatar answered Sep 30 '22 20:09

salathe


The most straightforward solution would be something like this.

$tokens = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

$serial = '';

for ($i = 0; $i < 4; $i++) {
    for ($j = 0; $j < 5; $j++) {
        $serial .= $tokens[rand(0, 35)];
    }

    if ($i < 3) {
        $serial .= '-';
    }
}

echo $serial;

Sample output:

51C8A-P9NZD-UM37Q-YKZHO
like image 35
blafrat Avatar answered Sep 30 '22 19:09

blafrat