PHPでUUID生成

なんかいろいろもやもやしている。

uuid-phpを使う

これなんのライブラリなんだろう?

yum -y install uuid-php

再起動。

service httpd restart

PHPソースコード

<?php
uuid_create(&$context);
uuid_make($context, UUID_MAKE_V1);

// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 形式。
uuid_export($context, UUID_FMT_STR, &$uuid);
echo $uuid . '<br>';

// バイト列。DBに入れたりするならこちらのがスリム。
uuid_export($context, UUID_FMT_BIN, &$uuid);
echo $uuid . '<br>'; // bin2hexすれば16進数の文字列にになる。

?>

Call-time pass-by-reference has been deprecated 
こういうエラーが出てしまうので、php.iniのallow_call_time_pass_referenceをOnにする。

再起動。

service httpd restart

どのバージョンを使うかはわかりやすいが、記法的に非推奨らしいので出来れば使いたくない…。

pecl uuid extensionを使う

事前に必要なものをインストールする。

yum -y install php-devel # for phpize
yum -y install gcc
yum -y install make
yum -y install libuuid-devel # for uuid.h

インストール。

pecl install uuid

php.iniに以下の行を追加する。

extension=uuid.so

再起動。

service httpd restart

PHPソースコード

<?php
echo uuid_create(UUID_TYPE_TIME) . '<br>';	// v1(Mac Address)っぽい
echo uuid_create(UUID_TYPE_RANDOM) . '<br>';	// v4(Random)っぽい
?>

使い方は簡単なんだが、いまいちタイプがどのバージョンを示すかわかりにくい。
出力された値を見てバージョンの判別は可能。

Universally unique identifier - Wikipedia

The variant indicates the layout of the UUID. The UUID specification covers one particular variant. Other variants are reserved or exist for backward compatibility reasons (e.g. for values assigned before the UUID specification was produced). An example of a UUID that is a different variant is the nil UUID, which is a UUID that has all 128 bits set to zero.

In the canonical representation, xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx, the most significant bits of N indicates the variant (depending on the variant; one, two or three bits are used). The variant covered by the UUID specification is indicated by the two most significant bits of N being 1 0 (i.e. the hexadecimal N will always be 8, 9, a, or b).

In the variant covered by the UUID specification, there are five versions. For this variant, the four bits of M indicates the UUID version (i.e. the hexadecimal M will either be 1, 2, 3, 4, or 5).