php 產生唯一id的幾種解決方案_PHP教程

來源:互聯網
上載者:User
網上查了下,有很多的方法

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

  這種方法有一定的機率會出現重複

2、php內建函數uniqid()

  uniqid() 函數基於以微秒計的目前時間,產生一個唯一的 ID.

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

  下面方法返回結果類似: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;
}
}

com_create_guid()是php內建的產生唯一id方法,php5之後貌似已經沒有了。
3、官方uniqid()參考手冊有使用者提供的方法,結果類似:{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;
}

http://www.bkjia.com/PHPjc/326742.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/326742.htmlTechArticle網上查了下,有很多的方法 1、md5(time() . mt_rand(1,1000000)); 這種方法有一定的機率會出現重複 2、php內建函數uniqid() uniqid() 函數基於以微秒計...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.