This article mainly introduces three methods for generating unique IDs in php. each method is simple and can help you generate unique IDs, interested friends can refer to the small series on the Internet to find a lot of articles on the php generation of unique id method, found that there are many ways, in this article, we will share with you the solutions to generate a unique id for php.
1. md5 (time (). mt_rand (1,000000 ));
There is a probability that this method will be repeated.
2. php built-in function uniqid ()
The uniqid () function generates a unique ID based on the current time in microseconds.
W3school reference manual has one sentence: "Because the system time is based, the ID generated through this function is not the best. To generate an absolutely unique ID, use the md5 () function ".
The returned result of the following method is similar to: 5ddb417f-4389-f4a9-a100-501ef1348872.
Function uuid () {if (function_exists ('com _ create_guid ') {return com_create_guid () ;}else {mt_srand (double) microtime () * 10000 ); // optional for php 4.2.0 and up. no need to sow data as needed after 4.2.0. $ Charid = strtoupper (md5 (uniqid (rand (), true); // generate a unique id based on the current time (in 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 );//. chr (125); // "}" return $ uuid ;}}
Com_create_guid () is the unique id method generated by php. it seems that php5 does not exist.
3. the official uniqid () reference manual has a user-provided method, the results are similar to: {E2DFFFB3-571E-6CFC-4B5C-9FEDAAF2EFD7}
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; }
The above are three solutions for generating a unique id in php, and hope to help you learn.