欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php 生成唯一id的幾種解決方法

 更新時(shí)間:2013年03月08日 16:00:04   投稿:shangke  
本篇文章介紹了“php 生成唯一id的幾種解決方法”,需要的朋友可以參考一下

網(wǎng)上查了下,有很多的方法

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

  這種方法有一定的概率會(huì)出現(xiàn)重復(fù)

2、php內(nèi)置函數(shù)uniqid()

  uniqid() 函數(shù)基于以微秒計(jì)的當(dāng)前時(shí)間,生成一個(gè)唯一的 ID.

  w3school參考手冊有一句話:"由于基于系統(tǒng)時(shí)間,通過該函數(shù)生成的 ID 不是最佳的。如需生成絕對唯一的 ID,請使用 md5() 函數(shù)"。

  下面方法返回結(jié)果類似: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.隨便數(shù)播種,4.2.0以后不需要了。
    $charid = strtoupper ( md5 ( uniqid ( rand (), true ) ) ); //根據(jù)當(dāng)前時(shí)間(微秒計(jì))生成唯一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;
  }
}

com_create_guid()是php自帶的生成唯一id方法,php5之后貌似已經(jīng)沒有了。
3、官方uniqid()參考手冊有用戶提供的方法,結(jié)果類似:{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;
 }

相關(guān)文章

最新評論