Home  >  Article  >  Backend Development  >  Several solutions to generate unique IDs in php_PHP tutorial

Several solutions to generate unique IDs in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:12:081322browse

I checked online and there are many methods

1. md5(time() . mt_rand(1,1000000));

This method has a certain probability of duplication

2. PHP built-in function uniqid()

The uniqid() function generates a unique ID based on the current time in microseconds.

There is a sentence in the w3school reference manual: "Because it is based on system time, the ID generated by this function is not optimal. If you need to generate an absolutely unique ID, please use the md5() function."

The following method returns similar results: 5DDB650F-4389-F4A9-A100-501EF1348872

Copy code The code is as follows:

function uuid() {
if (function_exists ( 'com_create_guid' )) {
                                                                                                                                                                                                                                                       Return com_create_guid (); .
         $charid = strtoupper ( md5 ( uniqid ( rand (), true) ) ); // Generate a unique id based on the current time (microseconds).
          $hyphen = chr (45); // "- "
$uuid = '' . //chr(123)// "{"
substr ( $charid, 0, 8 ) . $hyphen . substr ( $charid, 8, 4 ) . $hyphen . substr ($charid, 12, 4). $hyphen. substr ($charid, 16, 4). $hyphen. substr ($charid, 20, 12); }"
               return $uuid;
3. The official uniqid() reference manual has methods provided by users, and the results are similar: {E2DFFFB3-571E-6CFC-4B5C-9FEDAAF2EFD7}




Copy code

The code is as follows:

public function create_guid($namespace = '') { 

 static $guid = ''; $uid = uniqid("", true); $data = $namespace; $data .= $_SERVER['REQUEST_TIME']; $data .= $_SERVER ['HTTP_USER_AGENT'];
$data .= $_SERVER['LOCAL_ADDR'];
$data .= $_SERVER['LOCAL_PORT'];
$data .= $_SERVER['REMOTE_ADDR'] ;
$data .= $_SERVER['REMOTE_PORT'];
$hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
$guid = '{' .
substr($hash, 0, 8) .
'-' .
substr($hash, 8, 4) .
'-' .
substr($ hash, 12, 4) .
'-' .
substr($hash, 16, 4) .
'-' .
substr($hash, 20, 12) .
'}';
return $guid;
}






http://www.bkjia.com/PHPjc/326742.html

www.bkjia.com
true

http: //www.bkjia.com/PHPjc/326742.html

I checked online and there are many methods 1. md5(time() . mt_rand(1,1000000)) ; This method has a certain probability of duplication 2. PHP built-in function uniqid() uniqid() function is based on microseconds...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn