Several solutions for php to generate unique id

  • 2020-05-30 19:44:13
  • OfStack

Looked up on the Internet, there are a lot of ways

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

This method has a definite probability of being repeated

2. php built-in function uniqid()

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

The w3school reference manual has a sentence :" ID generated by this function is not optimal due to system time. To generate ID that is absolutely 1 only, use the md5() function ".

The following method returns a similar result: 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. Sow at random, 4.2.0 Not anymore. 
    $charid = strtoupper ( md5 ( uniqid ( rand (), true ) ) ); // Generate only according to the current time (microsecond meter) 1id.
    $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 generated only 1id method of php, which seems to have disappeared after php5.
3. The official uniqid() reference manual has methods provided by users, and the results are similar: {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;
 }


Related articles: