6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[php/Laravel]UUID生成

Last updated at Posted at 2018-04-15

目的

メール認証実装時に、URLのハッシュ値を生成するときに使用。
通常のuniqid()やハッシュ関数を組み合わせて汎用性の高い関数を作ってみた

使い方

  1. 以下のUUID.phpを作成 (例ではApp/Libsに配置)
  2. new UUID()で使用
    • MD5でhashしたいとき => new UUID('md5')
    • sha1でhashしたいとき => new UUID('sha1')

UUID.php

.php
<?php
/**
 * 限りなくuniqueに近いUUIDを生成する
 */

namespace App\Libs;


class UUID {

    /**
     * @var
     */
    public $prefix;

    /**
     * @var
     */
    public $entropy;

    /**
     * @param string $prefix
     * @param bool $entropy
     *
     */
    public function __construct($prefix = '', $entropy = false, $hash = null)
    {
        switch ($hash) {
            case 'md5': //32文字の16進数を返す
                //実行結果例:719deecdbfec1e13b4ed4e755ed39a47
                $this->uuid = md5(uniqid($prefix, $entropy));
                break;
            case 'sha1': //40文字の16進数を返す
                //実行結果例:ad46200ced3a5a5acd6697b11926589cc279b363
                $this->uuid = sha1(uniqid($prefix, $entropy));
                break;
            default: // $entropy:true 実行結果例:145677405658ddab75790ea7.19793837
                $this->uuid = uniqid($prefix, $entropy);
                break;
        }
    }

    /**
     * Limit the UUID by a number of characters
     *
     * @param $length
     * @param int $start
     * @return $this
     */
    public function limit($length, $start = 0)
    {
        $this->uuid = substr($this->uuid, $start, $length);

        return $this;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->uuid;
    }


}

使い方

1)prefixを付けたいとき

  • 第一引数にprefixテキストを渡す。
  • new UUID('prefix_',true)
    • 実行結果例:prefix_ad46200ced3a5a5acd6697b11926589cc279b363

2)$entropy付与

  • 第二引数にtrue/falseでentropy付与の選択が可能
  • entropyを使用すると、返り値に更に線形合同法を使用した値が付与される

これにより一意性がさらに増すとのこと PHP - uniqid

  • とはいっても理由無ければ使わなくても問題ないかと

3)ハッシュ関数選択

  • 第三引数にハッシュ名を渡す。
  • new UUID('',false,'MD5')
  • デフォルト(引数なし)ではuniqid()を使って生成する

使用例

laravelデフォルトだと生成tokenに'/'が混入してしまって、URLがおかしくなるので、そういうシーンにはいいかと

.php
    /**
     * Userパスワードリセットデータの作成
     */
    protected function create(array $data)
    {
        $email = $data['email'];
        $token = base64_encode(new UUID('',true));
        $this->token = $token;
        $created_at = Carbon::now();
        return PasswordReset::create(compact('email', 'token','created_at'));
    }
6
7
0

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
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?