TimGurney
9/25/2015 - 5:25 PM

Get the real IP address for a visitor.

Get the real IP address for a visitor.

<?php

function get_real_ip()
{
  foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key)
    {
      if (array_key_exists($key, $_SERVER) === true)
        {
          foreach (explode(',', $_SERVER[$key]) as $ip)
            {
              $ip = trim($ip);

              if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
                {
                  return ($ip);
                }
            }
        }
    }
}

Search through a set of server variables to see if a proxy is being used and to return the real IP address of the end user.