2016-05-19 11:12:08 0 Comments PHP Boy.Lee

php generate 100% unique random string demo code

In php web dev, we usually need use random string,for some conditions we need unique string. This topic show how to generate 100% unique random string and take cost in considered.

 

{ Random String Type }

a. Repeat in a Chance
b. 100%Unique Random String

 

{ a. Repeat in a Chance }

classical demo code:

$seed = [];
$seed['time'] = time();
$seed['ip'] = Yii::app()->request->userHostAddress; //get ip address in Yii
$seed['randNum'] = mt_rand(10000, 99999);
$randString = implode('_', $seed); 

echo $randString;//1463624229_127.0.0.1_41111

the above code use unixtimestamp+ip address as pre-condition,so we can only think one IP + one Sec. Then use 90000 random number(10000-99999) to control randon chance.

one IP + one Sec + 1/90000 Probability, is enough for normal size user system. FYI, the above code working like UUID no different, just for reading.

But,If you thinking in RESTful Architecture, like 100 servers system, the things are different.

If users from ip A can send 10k request per second. We can say the above code will not work anymore.

 

{ b. 100%Unique Random String }

In fact, b is easy than a, some time it's us that make things complex.

Let's think 1, 2, 3, 4. It's 4 unique string right?

If you want a little complex, we can use md5, like md5(1).

The Demo PHP Code:

$topic = new Topic();
//TODO add necessary attributes

if ($topic->save()) {
    $randString = md5($topic->t_id);
    
    echo $randString;//c20ad4d76fe97759aa27a0c99bff6710
}else{
    //save fail, do sth
}

We used DB server like MySQL in backend, MySQL has auto increment for auto+1, of cause we can do it in other way.

If want 100% unique randon string in some complex conditions, use one time simple db operate as exchange, it's acceptable.

Ok, This is just a little idea, if you have something want share, plz comment.