Skip to content

Instantly share code, notes, and snippets.

@lysender
Last active August 29, 2015 14:11
Show Gist options
  • Save lysender/9b84bf394fcfc9cf13dc to your computer and use it in GitHub Desktop.
Save lysender/9b84bf394fcfc9cf13dc to your computer and use it in GitHub Desktop.
<?php
class SomeUniqueId {
protected $strId = '';
public function __construct($ip, $timestamp = null)
{
$ids = array(
$this->generateLocationId(),
$this->generateHostId($ip),
$this->generateEpochId($timestamp),
$this->generateHexId(),
);
$this->strId = implode('-', $ids);
}
protected function generateLocationId()
{
// Not sure
return 'ECL00002';
}
protected function generateHostId($ip)
{
$ips = explode('.', $ip);
$ips = array_map('intval', $ips);
$i = (($ips[0] ^ $ips[1] ^ $ips[2]) << 8) | $ips[3];
return sprintf('%04x', $i);
}
protected function generateEpochId($timestamp = null)
{
if ($timestamp === null) {
$timestamp = time();
}
// Make sure they are integers
$timestamp = (int) $timestamp;
// Java equivalent handles thread safe stuff, but since PHP does not
// generally support threaded environment, no need for thread safety stuff
return dechex($timestamp);
}
protected function generateHexId()
{
// Not sure
$r = rand(0, 256);
return sprintf('%04x', ($r << 8));
}
public function __toString()
{
return $this->strId;
}
}
$id1 = new SomeUniqueId('127.0.0.1', time());
$id2 = new SomeUniqueId('10.0.2.1', time());
$id3 = new SomeUniqueId('192.168.100.101', time());
$id4 = new SomeUniqueId('250.220.210.251', time());
$id5 = new SomeUniqueId('251.252.253.250', time());
echo $id1."\n";
echo $id2."\n";
echo $id3."\n";
echo $id4."\n";
echo $id5."\n";
@lysender
Copy link
Author

Output:

[vagrant@localhost path2dx]$ php testuniqid.php
ECL00002-7f01-54903955-1300
ECL00002-0801-54903955-d600
ECL00002-0c65-54903955-f200
ECL00002-f4fb-54903955-b800
ECL00002-fafa-54903955-a000
[vagrant@localhost path2dx]$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment