首页 > 后端开发 > php教程 > php生成全球唯一标识符guid的算法示例

php生成全球唯一标识符guid的算法示例

WBOY
发布: 2016-07-25 08:57:18
原创
1052 人浏览过
本文介绍下,php生成全球唯一标识符guid的例子,有需要的朋友参考下。

1,创建php类库文件-guid.php

<?php
// guid.php
class System {
  function currentTimeMillis() {
    list($usec, $sec) = explode(" ",microtime());
    return $sec.substr($usec, 2, 3);
  }
}

class NetAddress {
  var $name = 'localhost';
  var $ip   = '127.0.0.1';
  function getHost($coumputer_name, $ip) { // static
    $address = new NetAddress();
    $address->name = $coumputer_name;
    $address->ip   = $ip;
    return $address;
  }

  function toString() {
    return strtolower($this->name.'/'.$this->ip);
  }
}

class Random {
  function nextLong() {
    $tmp = rand(0,1)?'-':'';
    return $tmp.rand(1000, 9999).rand(1000, 9999).rand(1000, 9999).rand(100, 999).rand(100, 999);
  }
}

class Guid{
  var $valueBeforeMD5;
  var $valueAfterMD5;
  function Guid($computer_name, $ip){
    $this->getGuid($computer_name, $ip);
  }
 //by bbs.it-home.org
 function getGuid($coumputer_name, $ip){
   $address = NetAddress::getHost($coumputer_name, $ip);
   $this->valueBeforeMD5 = $address->toString().':'.System::currentTimeMillis().':'.Random::nextLong();
   $this->valueAfterMD5 = md5($this->valueBeforeMD5);
  }
  
  function newGuid() {
   $Guid = new Guid();
   return $Guid;
  }
 
  function toString() {
   $raw = strtoupper($this->valueAfterMD5);
   return substr($raw,0,8).'-'.substr($raw,8,4).'-'.substr($raw,12,4).'-'.substr($raw,16,4).'-'.substr($raw,20);
  }
}
?>
登录后复制

2,调用示例,生成唯一的Gid:

<?php
require_once('guid.php'); //调用类库文件

$computer_name = $_SERVER["SERVER_NAME"];
$ip            = $_SERVER["SERVER_ADDR"];
$guid = new Guid($computer_name, $ip);
print $guid->toString();
//输出结果:3238D32E-807C-B1C4-01C4-FD1346D32110
?>
登录后复制


来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板