Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP code for generating decent-looking coupon codes (mix of letters and numbers)

Tags:

php

random

For an ecommerce site I want to generate a random coupon code that looks better than a randomly generated value. It should be a readable coupon code, all in uppercase with no special characters, only letters (A-Z) and numbers (0-9).

Since people might be reading this out / printing it elsewhere, we need to make this a simple-to-communicate value as well, perhaps 8-10 characters long.

Something like perhaps,

AHS3DJ6BW 
B83JS1HSK

(I typed that, so it's not really that random)

like image 454
QAQuest Avatar asked Aug 19 '10 12:08

QAQuest


2 Answers

$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$res = "";
for ($i = 0; $i < 10; $i++) {
    $res .= $chars[mt_rand(0, strlen($chars)-1)];
}

You can optimize this by preallocating the $res string and caching the result of strlen($chars)-1. This is left as an exercise to the reader, since probably you won't be generating thousands of coupons per second.

like image 124
Artefacto Avatar answered Sep 19 '22 23:09

Artefacto


Try this:

substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 10)
like image 38
Gumbo Avatar answered Sep 20 '22 23:09

Gumbo