PHP產生不重複標識符程式碼

來源:互聯網
上載者:User

PHP倒是內建了產生唯一id的函數:uniqid() ,它是基於目前時間微秒數的,用法如下:

 代碼如下 複製代碼
 echo uniqid(); //13位的字串
 echo uniqid("php_"); //當然你可以加上首碼
    echo uniqid("php_", TRUE); //如果第二個參數more_entropy為true則產生23位

字串

但是它產生的標識有可能不是唯一的,所以很多人會:

 代碼如下 複製代碼

<?php
    //這是第一種簡單的方法,當然用sha1()函數也可以。
    echo md5(uniqid());
    //第二種,利用時間戳記的方法
    echo md5(time() . mt_rand(1,1000000));
?>

例子。

 代碼如下 複製代碼

<?
//產生唯一識別碼

//sha1()函數, "安全散列演算法(SHA1)"

function create_unique() {
    $data = $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']
     .time() . rand();
    return sha1($data);
    //return md5(time().$data);

    //return $data;

}
?>

例子如下:

<?
$newhash = create_unique();
echo $newhash;
?>

我看到很多人使用 md5() 函數,即使它並不完全意味著這個目的:
 

 代碼如下 複製代碼

// generate unique string
echo md5(time() . mt_rand(1,1000000));

There is actually a PHP function named uniqid() that is meant to be used for this.

// generate unique string
echo uniqid();
/* prints
4bd67c947233e
*/

// generate another unique string
echo uniqid();
/* prints
4bd67c9472340
*/

你可能會注意到,儘管字串是唯一的,前幾個字元卻是類似的,這是因為產生的字串與伺服器時間相關。

但實際上也存在友好的一方面,由於每個新產生的 ID 會按字母順序排列,這樣排序就變得很簡單。
為了減少重複的機率,你可以傳遞一個首碼,或第二個參數來增加:
 

 代碼如下 複製代碼

// with prefix
echo uniqid('foo_');
/* prints
foo_4bd67d6cd8b8f
*/

// with more entropy
echo uniqid('',true);
/* prints
4bd67d6cd8b926.12135106
*/

// both
echo uniqid('bar_',true);
/* prints
bar_4bd67da367b650.43684647
*/

這個函數將產生比 md5() 更短的字串,節省一些空間。

php產生全球唯一識別碼(GUID)的方法

GUID在空間上和時間上具有唯一性,保證同一時間不同地方產生的數字不同。
世界上的任何兩台電腦都不會產生重複的 GUID 值。
需要GUID的時候,可以完全由演算法自動產生,不需要一個權威機構來管理。
GUID的長度固定,並且相對而言較短小,非常適合於排序、標識和儲存。

 代碼如下 複製代碼

<?php
//php產生GUID
function getGuid() {
 $charid = strtoupper(md5(uniqid(mt_rand(), true)));
 
 $hyphen = chr(45);// "-"
 $uuid = substr($charid, 0, 8).$hyphen
 .substr($charid, 8, 4).$hyphen
 .substr($charid,12, 4).$hyphen
 .substr($charid,16, 4).$hyphen
 .substr($charid,20,12);

 return $uuid;
}
?>

聯繫我們

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