IpUtils.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace AuthBundle\Utils;
  3. use Symfony\Component\HttpFoundation\IpUtils as SfIpUtils;
  4. class IpUtils
  5. {
  6. /**
  7. * @param string $clientIp
  8. * @param array $ips
  9. *
  10. * @return boolean
  11. */
  12. public function checkIp($clientIp, $ips = array())
  13. {
  14. // existe la variable de entorno API_CIDR ?
  15. // ej. API_CIDR = 127.0.0.1, 127.0.0.1-127.0.0.10, 127.0.0.1/24
  16. if (getenv("API_CIDR") !== false) {
  17. $API_CIDR = getenv("API_CIDR");
  18. $pieces = array_map('trim', explode(',', $API_CIDR));
  19. foreach ($pieces as $ip) {
  20. if (strpos($ip, '-') !== false) {
  21. $this->getIpRange($ip, $ips);
  22. } else {
  23. $ips[] = $ip;
  24. }
  25. }
  26. }
  27. foreach ($ips as $ip) {
  28. if (SfIpUtils::checkIp($clientIp, $ip)) {
  29. return true;
  30. }
  31. }
  32. return false;
  33. }
  34. /**
  35. * @param string $ipRange
  36. * @param array $ips
  37. *
  38. * @return array
  39. */
  40. public function getIpRange($ipRange, $ips = array())
  41. {
  42. $pieces = array_map('trim', explode('-', $ipRange));
  43. if (isset($pieces[0]) && isset($pieces[1])) {
  44. $firstIp = $ip = ip2long($pieces[0]);
  45. $lastIp = ip2long($pieces[1]);
  46. while ($ip <= $lastIp) {
  47. $ips[] = long2ip($ip);
  48. $ip++;
  49. }
  50. } elseif (isset($pieces[0])) {
  51. $ips[] = $pieces[0];
  52. }
  53. return $ips;
  54. }
  55. }