Algorithm example for php to generate globally unique identifier guid

WBOY
Release: 2016-07-25 08:57:18
Original
1047 people have browsed it
This article introduces an example of PHP generating a globally unique identifier guid. Friends in need can refer to it.

1. Create php class library file-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);
  }
}
?>
Copy after login

2, call the example and generate a unique 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
?>
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template