5
4

More than 3 years have passed since last update.

PHPでいい感じのランダム文字列を作る

Last updated at Posted at 2020-08-28

暗号学的にも強いランダムな文字列を作る方法。
他にもいろいろ方法があるけどひとまず openssl_random_pseudo_bytes() を使ってみた。

random.php
/**
 * 指定された桁数のランダム文字列を生成する
 * (古い環境では暗号学的な強さにならない場合もあるが、ほとんどの環境は問題ない)
 * 
 * @param int $length 求める文字列の長さ(桁数)
 * @param string $chars ランダム文字列に使用したい文字一覧
 */
function randomstr($length, $chars)
{
    $retstr = '';
    $data = openssl_random_pseudo_bytes($length);
    $num_chars = strlen($chars);
    for ($i = 0; $i < $length; $i++)
    {
        $retstr .= substr($chars, ord(substr($data, $i, 1)) % $num_chars, 1);
    }
    return $retstr;
}

// 16進数の範囲で16桁の文字列を生成する場合
$rand1 = randomstr(16, '0123456789ABCDEF');
// 32進数(Base32)の範囲で16桁の文字列を生成する場合
$rand2 = randomstr(16, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567');
// 英数大小文字の範囲で16桁の文字列を生成する場合
$rand3 = randomstr(16, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
5
4
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
5
4