LoginSignup
10
3

More than 5 years have passed since last update.

Laravelでランダムな文字列を生成する

Posted at

str_random.png

str_random ヘルパ関数を使います。第一引数に文字長を指定します。引数を省略した際のデフォルト文字長は16文字になります。

$randomString = str_random(30);

参考リンク

付録

内部実装は下記のようになっています。

    public static function random($length = 16)
    {
        $string = '';

        while (($len = strlen($string)) < $length) {
            $size = $length - $len;

            $bytes = random_bytes($size);

            $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
        }

        return $string;
    }

random_bytes関数はPHP7であれば内蔵の関数が使われますが、PHP5系ではこの関数が存在しないため、paragonie/random_compat パッケージがPolyfillとして使われます。

10
3
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
10
3