Search code examples
phpapachedrupaldrupal-7drupal-modules

How to write PHP code to evaluate client IP?


I have a Drupal 7.x website deployed and I need help with using the below function and returning a true/false based on IP (more info below). I am trying to use this in Drupal's Rules module.

Drupal comes with a built-in function..

<?php
  print ip_address();
?>

This returns the client's IP address in the form of an ipv4 address such as 172.16.14.100 (example). (https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/ip_address/7)

I need to be able to grab ip_address(); and evaluate it in PHP, i want the evaluation to return a boolean value (return TRUE) if the ip_address() is in the range of 172.16.1.1 - 172.16.255.255 and false if it is not.

Anyone able to help?


Solution

  • You could try using ip2long to change the IPv4 address into a long integer and use that for comparison.

    $example_ip = ip2long("192.168.1.1");
    $high_ip = ip2long("172.16.255.255");
    $low_ip = ip2long("172.16.1.1");
    if ($example_ip <= $high_ip && $low_ip <= $example_ip) {
      return true;
    }
    else {
        return false;
    }