欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

3种php生成唯一id的方法

程序员文章站 2023-12-31 09:43:34
...

这篇文章主要介绍了3种php生成唯一id的方法,每一个方法都很简单,都能帮助大家实现生成唯一id,感兴趣的小伙伴们可以参考一下

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

以上就是php生成唯一id的三种方案,希望对大家的学习有所帮助。

上一篇:

下一篇: