Random.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. namespace fast;
  3. /**
  4. * 随机生成类
  5. */
  6. class Random
  7. {
  8. /**
  9. * 生成数字和字母
  10. *
  11. * @param int $len 长度
  12. * @return string
  13. */
  14. public static function alnum($len = 6)
  15. {
  16. return self::build('alnum', $len);
  17. }
  18. /**
  19. * 仅生成字符
  20. *
  21. * @param int $len 长度
  22. * @return string
  23. */
  24. public static function alpha($len = 6)
  25. {
  26. return self::build('alpha', $len);
  27. }
  28. /**
  29. * 生成指定长度的随机数字
  30. *
  31. * @param int $len 长度
  32. * @return string
  33. */
  34. public static function numeric($len = 4)
  35. {
  36. return self::build('numeric', $len);
  37. }
  38. /**
  39. * 生成指定长度的无0随机数字
  40. *
  41. * @param int $len 长度
  42. * @return string
  43. */
  44. public static function nozero($len = 4)
  45. {
  46. return self::build('nozero', $len);
  47. }
  48. /**
  49. * 能用的随机数生成
  50. * @param string $type 类型 alpha/alnum/numeric/nozero/unique/md5/encrypt/sha1
  51. * @param int $len 长度
  52. * @return string
  53. */
  54. public static function build($type = 'alnum', $len = 8)
  55. {
  56. switch ($type) {
  57. case 'alpha':
  58. case 'alnum':
  59. case 'numeric':
  60. case 'nozero':
  61. switch ($type) {
  62. case 'alpha':
  63. $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  64. break;
  65. case 'alnum':
  66. $pool = '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ';
  67. break;
  68. case 'numeric':
  69. $pool = '0123456789';
  70. break;
  71. case 'nozero':
  72. $pool = '123456789';
  73. break;
  74. }
  75. return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len);
  76. case 'unique':
  77. case 'md5':
  78. return md5(uniqid(mt_rand()));
  79. case 'encrypt':
  80. case 'sha1':
  81. return sha1(uniqid(mt_rand(), true));
  82. }
  83. }
  84. /**
  85. * 获取全球唯一标识
  86. * @return string
  87. */
  88. public static function uuid()
  89. {
  90. return sprintf(
  91. '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
  92. mt_rand(0, 0xffff),
  93. mt_rand(0, 0xffff),
  94. mt_rand(0, 0xffff),
  95. mt_rand(0, 0x0fff) | 0x4000,
  96. mt_rand(0, 0x3fff) | 0x8000,
  97. mt_rand(0, 0xffff),
  98. mt_rand(0, 0xffff),
  99. mt_rand(0, 0xffff)
  100. );
  101. }
  102. }