开发者

Random code generator

I'd like to have a random code generator, written in PHP, that will generate a mixed case code similar to http://jsfiddle.net/UtKYn

Before I start re-inventing the wheel, perhaps someone can point me in the right direction.

Thanks.


UPDATE:

JS fiddle was just an example of the code they generate for each code project. Mixed case can increase the number of the combinations while keeping it fairly short.

I found the following function. What is the probability of it generating a duplicate? Do i need to add a db query to check for dupes against other codes stored in db?

function rand_string($min = "8", $max = "30") 
{
    $code = NULL;
    for($i=0;$i<$min;$i++) 
    {
        $char = chr(rand(48,122));
        while(!ereg("[a-zA-Z0-9]", $char))
        {
            if($char == $lchar) { continue; }
            $char = chr(rand(48,90));
        }
      $pass .= $char;
      $lchar = $char;
   开发者_开发百科 }
    return $pass;
}


Here is a simple Random String Generator the $characters can be any letters/numbers/special that you may wish. I have used this with all available characters special and regular. You would just pass the length of the random generated string that you want or a default of 8 characters will be generated. Just remove any characters that you wish not to use.

 function genRandomString($length = 8) {
     $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~!@#$%^&*()_+\|]}[{;:<,>.?/';
     $string = '';
     for ($p = 0; $p < $length; $p++) {
         $string .= $characters[mt_rand(0, strlen($characters)-1)];
     }
     return $string;
 }


The codes those sites are using are just basically base 32 id's. See http://en.wikipedia.org/wiki/Base32 for more information on that.

Regarding checking against unique keys, you will generally want to apply a unique key constraint on the fields, so yes, you either need to check your existing code exists, or check if the insertion failed. However, if you are using an auto increment id and converting it to base 32, you won't need to perform any checks since MySQL is generating a unique id for you.


Have a look at this post:

http://blog.kevburnsjr.com/php-unique-hash

It presents a method to create an alphanumeric hash that is unique and will not duplicate (at least until it cycles). This is a much better method than generated random numbers and testing for uniqueness.


I suppose that you want random string generation :

http://www.i-fubar.com/random-string-generator.php

http://www.lost-in-code.com/programming/php-code/php-random-string-with-numbers-and-letters/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜