PHP 获取当前客户端的IP地址,并判断是否在1.1.1.1 - 255.255.255.254区间

答案

  1. function getip()
  2. {
  3. $unknown = 'unknown';
  4. if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)) {
  5. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  6. } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) {
  7. $ip = $_SERVER['REMOTE_ADDR'];
  8. }
  9. /*
  10. 处理多层代理的情况
  11. 或者使用正则方式:$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
  12. */
  13. if (false !== strpos($ip, ','))
  14. $ip = reset(explode(',', $ip));
  15. return $ip;
  16. }
  17. $client_ip = getip();
  18. $client_ip = sprintf('%u', ip2long($client_ip)); //64位系统无压力
  19. /**
  20. * plan A
  21. */
  22. $range_min = sprintf('%u', ip2long('1.1.1.1'));
  23. $range_max = sprintf('%u', ip2long('255.255.255.255'));
  24. /**
  25. * plan B
  26. */
  27. $range_min = bindec(decbin(ip2long('1.1.1.1')));
  28. $range_max = bindec(decbin(ip2long('255.255.255.255')));
  29. if ($client_ip >= $range_min and $client_ip <= $range_max) {
  30. echo 'true';
  31. } else {
  32. echo 'false';
  33. }