Home >Backend Development >PHP Problem >How to generate unique id in php

How to generate unique id in php

Guanhui
GuanhuiOriginal
2020-05-01 15:39:184432browse

How to generate unique id in php

php method to generate unique id

1, PHP built-in function uniqid()

uniqid Used to obtain a prefixed unique ID based on the current time in microseconds.

uniqid ([ string $prefix = "" [, bool $more_entropy = false ]] ) : string

Note: This function does not guarantee the uniqueness of the return value. Since most systems use NTP or similar services to adjust the system's time, system time changes frequently. Additionally, the process/thread may not return a unique ID. Use more_entropy to increase the probability of uniqueness.

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;
  }
}

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

This method has a certain probability of duplication

The above is the detailed content of How to generate unique id in php. 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
Previous article:php string to timestampNext article:php string to timestamp