LoginSignup
4
6

More than 1 year has passed since last update.

【PHP】UUID生成

Last updated at Posted at 2022-07-11

はじめに

昔にUUIDを生成するプログラムを作成したが、最近ふとプログラムを見直した時にUUIDを生成していないことに気付いた。
今一度UUIDの生成方法を見直したのでその記録として残そうと思う。
ちなみに記述しているUUIDは全てversion4である。
※UUIDもどきはversion4のつもりで作成したがversion4になっていなかった…

UUIDの生成

パターン1

下記の方の記事を参考にしました。
JavaScriptでUUID4を実現させる

$pattern = "xxxxxxxx_xxxx_4xxx_yxxx_xxxxxxxxxxxx";
$character_array = str_split($pattern);
$uuid = "";

foreach($character_array as $character) {
    switch($character) {
        case "x":
            $uuid .= dechex(random_int(0, 15));
            break;

        case "y":
            $uuid .= dechex(random_int(8, 11));
            break;

        default:
            $uuid .= $character;
    }
}

var_dump($uuid); // e706a4ef_2a15_4145_a6a2_8a5cfc1cfe20

パターン2

●追記 2022年7月16日
こちらのコードですが、コメント欄で@prc990さんに教えて頂きました。

echo preg_replace_callback(
  '/x|y/',
  function($m) {
    return dechex($m[0] === 'x' ? random_int(0, 15) : random_int(8, 11));
  },
  'xxxxxxxx_xxxx_4xxx_yxxx_xxxxxxxxxxxx'
);

// c66a8d6c_f74f_4267_91c3_0c36a5bfb017

UUIDもどきの生成

// 下記を変換してますがUUIDのバージョン4になっていない...
// xxxxxxxx_xxxx_4xxx_yxxx_xxxxxxxxxxxx → %04x%04x-%04x-%04x-%04x-%04x%04x%04x
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
var_dump($uuid); // ac87b6c7-b014-1454-f6e7-4660ca57f395

ちなみに、%0(桁数)は桁数指定をしています。
例えば、%0(桁数)xの場合、10進数の「1000」を16進数変換すると「3e8」ですが0が入り「03e8」になります。.
0埋めで桁数を揃えたい場合にも使用できます。

おまけ

Laravelだと下記のように記述することができます。

use Illuminate\Support\Str;
 
return (string) Str::uuid();

参考文献

rfc4122
UUID(Wikipedia)
Laravel:helpers#method-str-uuid
JavaScriptでUUID4を実現させる

4
6
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6