LoginSignup
1
1

More than 5 years have passed since last update.

【PHP5】uniqid()関数を使用して、ユニーク(一意)なIDを生成する

Last updated at Posted at 2018-05-13
uniqid.php

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>ユニークなタイトルIDを生成</title>
    <!-- emmet->meta:vp -->
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
</head>
<body>
    <?php 
    // ユニークIDは、マイクロ秒(100万分の1秒)単位で変化。

    // ユニークな13桁のIDを出力する
    // 出力結果「5af8cdbe59ff3」
    // 出力結果「5af8cdbe5a019」
    echo uniqid()."<br>";
    echo uniqid()."<br>";
    // 先頭に「test_」とついたユニークなIDを作成する
    // 出力結果「test_5af8cdbe5a03e」
    // 出力結果「test_5af8cdbe5a062」
    echo uniqid('test_')."<br>";
    echo uniqid('test_')."<br>";
    // より推測の難しい文字列を生成
    // この場合、23文字
    // 出力結果「5af8cdbe5a07e9.81077980」
    // 出力結果「5af8cdbe5a09e0.53166384」
    // 出力結果「5af8cdbe5a0b92.42877045」
    echo uniqid('',true)."<br>";
    echo uniqid('',true)."<br>";
    echo uniqid('',true)."<br>";
    // 頭に「test_」のついたユニークなIDを生成
    // 出力結果「test_5af8cdbe5a0d39.05814345」
    // 出力結果「test_5af8cdbe5a0ee7.93872758」
    echo uniqid('test_',true)."<br>";
    echo uniqid('test_',true)."<br>";
    // mt_rand()で乱数を生成->同じマイクロ秒でも異なる文字列を生成できる
    // md5()->md5ハッシュ値を計算。パスワードのハッシュ化には向いていない
    // 出力結果「4020dd107cffde2aa9b8e52787b98b13」
    // 出力結果「27a5a8778381c73817d5ffc3215a4073」
    echo md5(uniqid(mt_rand(),true))."<br>";
    echo md5(uniqid(mt_rand(),true))."<br>";

    // uniqid()関数は、暗号学的に安全な文字列ではない。
    // 暗号学的に安全な値が必要な場合は、openssl_random_pseudo_bytes()関数を使う。
     ?>
</body>
</html>

参考書籍

PHP逆引き辞典

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