common.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. <?php
  2. // 应用公共文件
  3. /**
  4. * 获取客户端IP地址
  5. * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
  6. * @param boolean $adv 是否进行高级模式获取(有可能被伪装)
  7. * @return mixed
  8. */
  9. function get_client_ip($type = 0, $adv = true)
  10. {
  11. $type = $type ? 1 : 0;
  12. static $ip = null;
  13. if ($ip !== null) {
  14. return $ip[$type];
  15. }
  16. if ($adv) {
  17. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  18. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  19. $pos = array_search('unknown', $arr);
  20. if (false !== $pos) {
  21. unset($arr[$pos]);
  22. }
  23. $ip = trim($arr[0]);
  24. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  25. $ip = $_SERVER['HTTP_CLIENT_IP'];
  26. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  27. $ip = $_SERVER['REMOTE_ADDR'];
  28. }
  29. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  30. $ip = $_SERVER['REMOTE_ADDR'];
  31. }
  32. // IP地址合法验证
  33. $long = sprintf("%u", ip2long($ip));
  34. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  35. return $ip[$type];
  36. }