0

I am facing an issue where I am unable to determine the client's IP address correctly.

I have gone through the following question How to get the client IP address in PHP? but this does not resolve my situation.

Requirement is as given below.

  1. If the visitor connects from IPv4 address, the script should show me the client's IPv4 address (This is handled in the script given below)
  2. If the visitor connects from IPv6 address, the script should show me the client's IPv6 address (The script given below converts the IPv6 address to IPv4 and does not give me the correct IPv6 address)

Given below is the script to capture the client's IP address.

<?php
function get_client_ip() 
{
   $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';

   return $ipaddress;
} 
echo get_client_ip();
?>

Do I need to tweak PHP/Ubuntu/NGINX configuration or possibly A records?

Can anybody please point me out what am I missing to achieve this functionality? I am on PHP7, Ubuntu 16.04 and NGINX

Thanks

Community
  • 1
  • 1
user4943000
  • 111
  • 12
  • is `ipv6` enabled on your server? also, you should try putting `if(getenv('REMOTE_ADDR'))` on the top. – Pedro Lobito Apr 25 '17 at 16:21
  • Possible duplicate of [How to get the client IP address in PHP?](http://stackoverflow.com/questions/3003145/how-to-get-the-client-ip-address-in-php) – Pedro Lobito Apr 25 '17 at 16:25
  • @PedroLobito: I issued the following command `test -f /proc/net/if_inet6 && echo "IPv6 supported" || echo "IPv6 not supported" ` in Shell and got the response "IPv6 supported". I had also gone through the link you gave earlier, but it resolves a different requirement. Mine is that I get IPv4 addresses even when I connect from IPv6 connection. – user4943000 Apr 25 '17 at 16:40
  • Also as per your suggestion, I echoed `getenv('REMOTE_ADDR')` at the beginning and still getting the same results. – user4943000 Apr 25 '17 at 16:43

0 Answers0