helpers.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. // 生成SS密码
  3. if (!function_exists('makeRandStr')) {
  4. function makeRandStr($length = 8)
  5. {
  6. // 密码字符集,可任意添加你需要的字符
  7. $chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789';
  8. $char = '';
  9. for ($i = 0; $i < $length; $i++) {
  10. $char .= $chars[mt_rand(0, strlen($chars) - 1)];
  11. }
  12. return $char;
  13. }
  14. }
  15. // base64加密(处理URL)
  16. if (!function_exists('base64url_encode')) {
  17. function base64url_encode($data)
  18. {
  19. return strtr(base64_encode($data), ['+' => '-', '/' => '_', '=' => '']);
  20. }
  21. }
  22. // base64解密(处理URL)
  23. if (!function_exists('base64url_decode')) {
  24. function base64url_decode($data)
  25. {
  26. return base64_decode(strtr($data, '-_', '+/'));
  27. }
  28. }
  29. // 根据流量值自动转换单位输出
  30. if (!function_exists('flowAutoShow')) {
  31. function flowAutoShow($value = 0)
  32. {
  33. $kb = 1024;
  34. $mb = 1048576;
  35. $gb = 1073741824;
  36. $tb = $gb * 1024;
  37. $pb = $tb * 1024;
  38. if (abs($value) > $pb) {
  39. return round($value / $pb, 2) . "PB";
  40. } elseif (abs($value) > $tb) {
  41. return round($value / $tb, 2) . "TB";
  42. } elseif (abs($value) > $gb) {
  43. return round($value / $gb, 2) . "GB";
  44. } elseif (abs($value) > $mb) {
  45. return round($value / $mb, 2) . "MB";
  46. } elseif (abs($value) > $kb) {
  47. return round($value / $kb, 2) . "KB";
  48. } else {
  49. return round($value, 2) . "B";
  50. }
  51. }
  52. }
  53. if (!function_exists('toMB')) {
  54. function toMB($traffic)
  55. {
  56. $mb = 1048576;
  57. return $traffic * $mb;
  58. }
  59. }
  60. if (!function_exists('toGB')) {
  61. function toGB($traffic)
  62. {
  63. $gb = 1048576 * 1024;
  64. return $traffic * $gb;
  65. }
  66. }
  67. if (!function_exists('flowToGB')) {
  68. function flowToGB($traffic)
  69. {
  70. $gb = 1048576 * 1024;
  71. return $traffic / $gb;
  72. }
  73. }
  74. // 文件大小转换
  75. if (!function_exists('formatBytes')) {
  76. function formatBytes($bytes, $precision = 2)
  77. {
  78. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  79. $bytes = max($bytes, 0);
  80. $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
  81. $pow = min($pow, count($units) - 1);
  82. $bytes /= pow(1024, $pow);
  83. return round($bytes, $precision) . ' ' . $units[$pow];
  84. }
  85. }