php 生成唯一id的几种解决方法

来源:互联网 发布:mac finally free 编辑:程序博客网 时间:2024/05/22 00:35

<?php
UUID是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的。通常平台 会提供生成UUID的API。UUID按照开放软件基金会(OSF)制定的标准计算,用到了以太网卡地址、纳秒级时间、芯片ID码和许多可能的数字。由以 下几部分的组合:当前日期和时间(UUID的第一个部分与时间有关,如果你在生成一个UUID之后,过几秒又生成一个UUID,则第一个部分不同,其余相 同),时钟序列,全局唯一的IEEE机器识别号(如果有网卡,从网卡获得,没有网卡以其他方式获得),UUID的唯一缺陷在于生成的结果串会比较长。关于 UUID这个标准使用最普遍的是微软的GUID(Globals Unique Identifiers)。
在ColdFusion中可以用CreateUUID()函数很简单的生成UUID,其格式为:xxxxxxxx-xxxx-xxxx- xxxxxxxxxxxxxxxx(8-4-4-16),其中每个 x 是 0-9 或 a-f 范围内的一个十六进制的数字。而标准的UUID格式为:xxxxxxxx-xxxx-xxxx-xxxxxx-xxxxxxxxxx (8-4-4-4-12)


function guid(){
    if (
function_exists('com_create_guid'
)){
        return
 com_create_guid
();
    }else{
        
mt_srand((double)microtime()*10000);
//optional for php 4.2.0 and up.
        
$charid = strtoupper(md5(uniqid(rand(), true
)));
        
$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
;
    }
}
echo
 guid
();
?>



其他的方法

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;
  }
0 0
原创粉丝点击