LoginSignup
0
0

More than 1 year has passed since last update.

PHP 任意の文字、文字数でランダムな文字列を生成する

Last updated at Posted at 2022-04-06

コード

random.php
<?php declare(strict_types=1);

class Str
{
    private const CHARS = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_/*+.,!#$%&()~|';

    /**
     * @param int $length
     * @return string
     */
    public static function random(int $length): string
    {
        return substr(str_shuffle(str_repeat(self::CHARS, $length)), 0, $length);
    }
}

echo Str::random(8), PHP_EOL;
echo Str::random(16), PHP_EOL;
echo Str::random(32), PHP_EOL;

補足1

CHARS に指定した文字でランダムな文字列を生成します。
使いたくない文字は取り除いてください。

str_repeat を使ってるのは、指定しないと CHARS で定義された文字数までの文字列しか作れないことと、同じ文字が2回以上表示されないためです。
https://www.php.net/manual/ja/function.str-repeat.php

str_shuffle は暗号学的には安全ではないので、暗号の値としては使えません。
https://www.php.net/manual/ja/function.str-shuffle.php

補足2

小文字の英字と数字のみで良い場合はrandom-bytesを使った方が良さそう。

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