PHP code for generating decent-looking coupon code

2019-01-23 15:25发布

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)

标签: php random
10条回答
小情绪 Triste *
2楼-- · 2019-01-23 15:58
$length = 9;
$code   = (strtoupper(substr(md5(time()), 0, $length)));
查看更多
SAY GOODBYE
3楼-- · 2019-01-23 16:02

If there are no security requirements for these, then you don't really need randomly generated codes. I would just use incremental IDs, such as those generated by whatever RDBMS you use. Optionally, if you have different types of coupons, you could prefix the codes with something, e.g.:

CX00019 QZ0001C
CX0001A QZ0001D
CX0001B QZ0001E

Alternately, you could even use dictionary words in the coupon, as such coupon codes are easier to remember and faster for users to type. Companies like Dreamhost use these for their promo codes, e.g.:

Promo60
NoSetupFee
YELLOWGORILLA82

Some of these are obviously human-created (which you might want to have the option of), but they can also be generated using a dictionary list. But even if they are randomly-generated nonsense phrases, the fact that the characters follow a logical pattern still makes it much more user-friendly than something like R7QZ8A92F1. So I would strongly advise against using the latter type of coupon codes just on the basis that they "look cool". Your customers will thank you.

查看更多
你好瞎i
4楼-- · 2019-01-23 16:02

you can find a lot of function in php rand manual
http://php.net/manual/en/function.rand.php

i like this one

   <?php
//To Pull 8 Unique Random Values Out Of AlphaNumeric

//removed number 0, capital o, number 1 and small L
//Total: keys = 32, elements = 33
$characters = array(
"A","B","C","D","E","F","G","H","J","K","L","M",
"N","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9");

//make an "empty container" or array for our keys
$keys = array();

//first count of $keys is empty so "1", remaining count is 1-7 = total 8 times
while(count($keys) < 8) {
    //"0" because we use this to FIND ARRAY KEYS which has a 0 value
    //"-1" because were only concerned of number of keys which is 32 not 33
    //count($characters) = 33
    $x = mt_rand(0, count($characters)-1);
    if(!in_array($x, $keys)) {
       $keys[] = $x;
    }
}

foreach($keys as $key){
   $random_chars .= $characters[$key];
}
echo $random_chars;
?>
查看更多
该账号已被封号
5楼-- · 2019-01-23 16:04
$size = 12;

$string = strtoupper(substr(md5(time().rand(10000,99999)), 0, $size));
查看更多
登录 后发表回答