Home  >  Article  >  Backend Development  >  php generates unique ids

php generates unique ids

(*-*)浩
(*-*)浩Original
2019-09-27 10:13:122582browse

To generate unique and non-duplicate identifiers, we mainly use the current time and then convert it to the md5 value. This can almost guarantee the uniqueness of the label. Here is some program code for generating non-duplicate identifiers in PHP

php generates unique ids

php built-in function uniqid()

## The uniqid() function is based on the current time in microseconds, Generate a unique ID. (Recommended learning: PHP programming from entry to proficiency)

w3school reference manual has a sentence: "

Because it is based on the system time, through the The ID generated by the function is not optimal. To generate an absolutely unique ID, use the md5() function. The following method returns similar results: 5DDB650F-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.随便数播种,4.2.0以后不需要了。
        $charid = strtoupper ( md5 ( uniqid ( rand (), true ) ) ); //根据当前时间(微秒计)生成唯一id.
        $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;
    }
}

php method to generate a globally unique identifier (GUID)

GUID is unique in space and time, ensuring that different numbers generated in different places at the same time are different.

No two computers in the world will generate duplicate GUID values.

When a GUID is required, it can be completely automatically generated by the algorithm and does not require an authoritative organization to manage it.

GUID has a fixed length and is relatively short, which is very suitable for sorting, identification and storage.

<?php
//php生成GUID
function getGuid() {
 $charid = strtoupper(md5(uniqid(mt_rand(), true)));
 
 $hyphen = chr(45);// "-"
 $uuid = 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;
}
?>

The above is the detailed content of php generates unique ids. For more information, please follow other related articles on the PHP Chinese website!

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