使用PHP uniqid函數產生唯一ID_php執行個體

來源:互聯網
上載者:User

產生唯一ID的應用情境非常普遍,如臨時快取檔案名稱,臨時變數,臨時安全碼等,uniqid()函數基於以微秒計的目前時間,產生一個唯一的 ID。由於產生唯一ID與微秒時間關聯,因此ID的唯一性非常可靠。

產生的唯一ID預設返回的字串有 13 個字串長,如果不定義唯一ID的首碼,最多可返回23個字串長,如果再結合md5()函數,產生的唯一ID可靠性將更高,這種產生的ID比隨機性的ID 最大優點在於可實現排序,特別是一些需要儲存在資料庫中的值。

一,函數原型

string uniqid ( [string prefix [, bool more_entropy]] )

可定義唯一ID的首碼與長度

二,版本相容

PHP 3, PHP 4, PHP 5

三,函數基礎用法與執行個體

1,產生一個唯一ID

<?php echo uniqid(); ?> 

2,結合md5()函數產生一個唯一ID

<?php echo md5(uniqid()); ?> 

輸出:dfbc5c8c6438de075da28b3c8a413fd0

3,產生多個唯一ID,由於是以微秒計

<?php echo uniqid(); echo uniqid(); echo uniqid(); ?> 

輸出:

4bfd0e375396b
4bfd0e3753981
4bfd0e3753983

由產生的結果來看,唯一ID之間具有可排序性的。
使用uniqid()函數產生唯一ID既能用於產生臨時性ID也能用於產生永久性唯一ID(儲存資料庫)。

ps:php 產生唯一id的幾種解決方案

下面小編給大家整理了三種解決辦法,具體內容如下:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.