I poked around online the other day looking for some PHP code that would do things like tell me whether or not a user was using IPv6. I found some code that did the job after a bit of Googling.

The code was pretty ugly, so I fixed it up. While I was at it, I updated it to optimize it a bit, as well as use conventions found in newer versions of PHP, such as the $_SERVER[] variable array, etc. Further, since I only needed to detect whether or not a user was using IPv6, I was able to cut the code that did IPv6 address compression and uncompression.


<?php
class ipv6 {
  function is_ipv6($ip) {
    if (!$ip) {
      $ip = ipv6::get_ip();
    }
    if (preg_match('/:/', $ip) && !(preg_match('/./', $ip))) {
      return true;
    } else {
      return false;
    }
  }

  function is_ipv4($ip) {
    return !ipv6::is_ipv6($ip);
  }

  function get_ip() {
    return $_SERVER['REMOTE_ADDR'];
  }
}
?>