Utils.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace common\helpers;
  3. use Yii;
  4. class Utils
  5. {
  6. /**
  7. * 获取一级域名
  8. * @return mixed|string
  9. */
  10. public static function getTopDomain()
  11. {
  12. $hostInfo = Yii::$app->getRequest()->getHostInfo();
  13. $host = parse_url($hostInfo, PHP_URL_HOST);
  14. $hostArr = explode('.', $host);
  15. $hostArr = array_reverse($hostArr);
  16. if (count($hostArr) >= 2) {
  17. return "{$hostArr[1]}.{$hostArr[0]}";
  18. } else {
  19. return $host;
  20. }
  21. }
  22. /**
  23. * 格式化整数、浮点数
  24. * @param $number
  25. * @param int $decimals
  26. * @return int|string
  27. */
  28. public static function formatFloatOrInt($number, $decimals = 2)
  29. {
  30. if (!is_numeric($number)) {
  31. return $number;
  32. }
  33. if (intval($number) == $number) {
  34. return intval($number);
  35. } else {
  36. return number_format($number, $decimals, '.', '');
  37. }
  38. }
  39. /**
  40. * 校验手机号码格式
  41. * @param string $phone
  42. * @return bool
  43. */
  44. public static function checkPhoneNumber($phone)
  45. {
  46. return preg_match('/^1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\d{8}$/', $phone) != false;
  47. }
  48. /**
  49. * 获取客户端IP地址
  50. * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
  51. * @return mixed
  52. */
  53. public static function getClientIp($type = 0)
  54. {
  55. $type = $type ? 1 : 0;
  56. static $ip = NULL;
  57. if ($ip !== NULL) return $ip[$type];
  58. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  59. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  60. $pos = array_search('unknown', $arr);
  61. if (false !== $pos) unset($arr[$pos]);
  62. $ip = trim($arr[0]);
  63. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  64. $ip = $_SERVER['HTTP_CLIENT_IP'];
  65. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  66. $ip = $_SERVER['REMOTE_ADDR'];
  67. }
  68. // IP地址合法验证
  69. $long = sprintf("%u", ip2long($ip));
  70. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  71. return $ip[$type];
  72. }
  73. }