RequestID.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace app\http;
  3. class RequestID
  4. {
  5. /**
  6. * 生成唯一请求id
  7. * @return string
  8. */
  9. public static function generate()
  10. {
  11. // 使用uniqid()方法创建唯一id
  12. $request_id = strtoupper(md5(uniqid($_SERVER['HTTP_USER_AGENT'],true)));
  13. // 格式化请求id
  14. return self::format($request_id);
  15. }
  16. /**
  17. * 格式化请求id
  18. *
  19. * @param string $request_id 请求id
  20. * @param string $format 格式
  21. *
  22. * @return string
  23. */
  24. private static function format($request_id, $format='16,4,4'){
  25. $tmp = array();
  26. $offset = 0;
  27. $cut = explode(',', $format);
  28. // 根据设定格式化
  29. if($cut){
  30. foreach($cut as $v){
  31. $tmp[] = substr($request_id, $offset, $v);
  32. $offset += $v;
  33. }
  34. }
  35. // 加入剩余部分
  36. if($offset<strlen($request_id)){
  37. $tmp[] = substr($request_id, $offset);
  38. }
  39. return implode('_', $tmp);
  40. }
  41. }