code.fastix.org

Dateiansicht:

Datei:Projekte -> PHP:UUID_v4 -> uuid_v4.php
md5:f82547ee4aa8cfbd7e174d6ba47c4c25
sha1:8e2014bbb60e0b634ce6ffd1cd976977f779d1ea
Download-Link:Download
  1. <?php
  2.  
  3. class uuid_v4 {
  4.  
  5. /*  Show:
  6.         RFC rfc4122, July 2005
  7.         Section 4.4.: 'Algorithms for Creating a UUID from Truly Random or Pseudo-Random Numbers'
  8. */
  9.     private $uuid_v4 = false;
  10.  
  11.     function __construct ( $gen = true ) {
  12.         if ( $gen ) {
  13.             $this -> gen_uuid_v4();
  14.         }
  15.     }
  16.  
  17.     public function gen_uuid_v4() {
  18.         $a = array();
  19.         $a[] = mt_rand( 0, 0xffff ) + ( mt_rand( 0, 0xffff ) << 16 );
  20.         $a[] = mt_rand( 0, 0xffff );
  21.         $a[] = (4 << 12) | ( mt_rand( 0, 0x1000 ) );
  22.         $a[] = ( 1 << 7 ) | ( mt_rand( 0, 0xf0 ) );
  23.         $a[] = mt_rand( 0, 0xff );
  24.  
  25.         for ( $i = 0; $i < 6; $i++ ) {
  26.             $a[] = mt_rand( 0, 0xf8 );
  27.         }
  28.  
  29.         $this -> uuid_v4 = sprintf(
  30.             '%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x', $a[0], $a[1], $a[2], $a[3], $a[4], $a[5], $a[6], $a[7], $a[8], $a[9],$a[10]
  31.         );
  32.     }
  33.  
  34.     public function get_uuid() {
  35.         if ( false == $this -> uuid_v4 ) {
  36.             $this -> uuid_v4 = $this -> gen_uuid_v4();
  37.         }
  38.         return $this -> uuid_v4;
  39.     }
  40.  
  41.     public function get_new_uuid() {
  42.         $this -> gen_uuid_v4();
  43.         return $this -> uuid_v4;
  44.     }
  45.    
  46.     public function test_uuid( $uuid ) {
  47.    
  48.         $subject  = strtolower($uuid);
  49.         $hexchars = '[0-9a-f]';
  50.         $hexcharsLimited = '[89abcdef]';
  51.         $pattern  = '/^' . $hexchars . '{8}'
  52.                   . '-'  . $hexchars . '{4}'
  53.                   . '-'  . $hexchars . '{4}'
  54.                   . '-'  . $hexcharsLimited . $hexchars . '{3}'
  55.                   . '-'  . $hexchars . '{12}' . '$/';
  56.         if ( 1 == preg_match ( $pattern , $subject ) ) {
  57.             return true;
  58.         } else {
  59.             return false;
  60.         }
  61.     }
  62.  
  63. }
  64.  
  65.  
  66. ##################### Test/Usage ###############################
  67. /*
  68. $oUuid = new uuid_v4;
  69. for ($i = 0; $i<10; $i++ ) {
  70.     $uuid = $oUuid -> get_new_uuid();
  71.     $t =  'false';
  72.     if ( $oUuid -> test_uuid( $uuid ) ) $t = 'true';
  73.     echo $uuid . ' ( ' . $t . " )\n";
  74. }
  75. echo "-----------------------------\n";
  76. $oUuid = new uuid_v4();
  77. for ($i = 0; $i<10; $i++ ) {
  78.     echo $oUuid -> get_uuid() . "\n";
  79. }
  80. #*/