Skip to content

Instantly share code, notes, and snippets.

@avtaniket
Created June 26, 2015 05:46
Show Gist options
  • Save avtaniket/35ca86b3eb8e606a1a0c to your computer and use it in GitHub Desktop.
Save avtaniket/35ca86b3eb8e606a1a0c to your computer and use it in GitHub Desktop.
GUID - unique key generation script to save as primary key in Tables
<?php
/**
* determines if a passed string matches the criteria for a GUID
* @param string $guid
* @return bool false
*/
function is_guid($guid)
{
return strlen($guid) == 36 && preg_match("/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i", $guid);
}
/**
* Generate GUID
* @return String contianing a GUID in the format: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
*/
function create_guid()
{
$microTime = microtime();
list($a_dec, $a_sec) = explode(" ", $microTime);
$dec_hex = dechex($a_dec* 1000000);
$sec_hex = dechex($a_sec);
ensure_length($dec_hex, 5);
ensure_length($sec_hex, 6);
$guid = "";
$guid .= $dec_hex;
$guid .= create_guid_section(3);
$guid .= '-';
$guid .= create_guid_section(4);
$guid .= '-';
$guid .= create_guid_section(4);
$guid .= '-';
$guid .= create_guid_section(4);
$guid .= '-';
$guid .= $sec_hex;
$guid .= create_guid_section(6);
return $guid;
}
function create_guid_section($characters)
{
$return = "";
for ($i=0; $i<$characters; $i++) {
$return .= dechex(mt_rand(0,15));
}
return $return;
}
function ensure_length(&$string, $length)
{
$strlen = strlen($string);
if ($strlen < $length) {
$string = str_pad($string,$length,"0");
} elseif ($strlen > $length) {
$string = substr($string, 0, $length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment