note 112179 added to function.uniqid

From: Date: Tue, 14 May 2013 09:55:19 +0000
Subject: note 112179 added to function.uniqid
Groups: php.notes 
Request: Send a blank email to php-notes+get-194801@lists.php.net to get a copy of this message
这个函数是用来生成一个基于时间的全局唯一标识,mac地址使用ip地址代替。 你也可以把空闲的两个字节设置成项目代号,或者记录类型之类的。 这样通过标识,就可以知道这是什么类型的数据,什么时间创建,哪台主机生成。 <?php /** * 创建一个基于时间的全局唯一标识 UUID v1 * http://www.ietf.org/rfc/rfc4122.txt * * @param number $prefix * 取值范围是 0~65535 之间。 * 可以用作标识记录类型,或者项目代号。 * @return string */ function newID ( $prefix = 0 ) { // 静态变量用于计数 static $ticks = 0; static $clock = null; // 初始随机种子 is_null( $clock ) && $clock = rand( 0, 0x3FFF ); // 确保0.0000001秒内创建16383个标识不会重复 $ticks++; // 进行时间转换 UUID 使用的是 1582-10-15 00:00:00.00 $microtime = microtime(); $timestamp = subStr( $microtime, -10 ) . subStr( $microtime, 2, 7 ); $uuidTime = bcadd( $timestamp, '122192928000000000' ); $sequence = $clock ^ $ticks | 0x8000; // subStr 为了防止若干年后因长度变化导致错误 $t1_t2_t3 = subStr( str_pad( base_convert( $uuidTime, 10, 16 ) , 15, '0', STR_PAD_LEFT ), -15 ); $t1 = substr( $t1_t2_t3, 7, 8 ); $t2 = substr( $t1_t2_t3, 3, 4 ); $t3 = substr( $t1_t2_t3, 0, 3 ); // IIS7 平台下没有 $_SERVER['SERVER_ADDR'] $serverAdr = isset( $_SERVER['SERVER_ADDR'] ) ? $_SERVER['SERVER_ADDR'] : $_SERVER['LOCAL_ADDR']; list( $i1, $i2, $i3, $i4 ) = explode( '.', $serverAdr ); // 返回结果 return sPrintF( "%s-%s-1%s-%04x-%04x%02x%02x%02x%02x", $t1, $t2, $t3, $sequence, $prefix, $i1, $i2, $i3, $i4 ); } // 测试代码 for( $i=0; $i<999; $i++ ) { echo newID( 0xD100 ); echo "<br />"; } ?> ---- Server IP: 69.147.83.199 Probable Submitter: 123.122.16.77 ---- Manual Page -- http://php.net/manual/en/function.uniqid.php Edit -- https://master.php.net/note/edit/112179 Del: integrated -- https://master.php.net/note/delete/112179/integrated Del: useless -- https://master.php.net/note/delete/112179/useless Del: bad code -- https://master.php.net/note/delete/112179/bad+code Del: spam -- https://master.php.net/note/delete/112179/spam Del: non-english -- https://master.php.net/note/delete/112179/non-english Del: in docs -- https://master.php.net/note/delete/112179/in+docs Del: other reasons-- https://master.php.net/note/delete/112179 Reject -- https://master.php.net/note/reject/112179 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#194801) next »