PHP: Determine or Retrieve Visitor’s IP Address Using PHP Script

How do I determine or retrieve visitor’s IP address using PHP server side programming under Unix/Windows operating systems?

Use the following environment variables to get visitor’s IP address:

No Proxy detection
REMOTE_ADDR – Get the remote client IP address

With Proxy detection
HTTP_X_FORWARDED_FOR – Get the proxy server IP address.

PHP getenv() function
Use php getenv() function to read the value of the environment. The syntax is:

getenv('VAR-NAME-HERE')

Example: Sample code to get an IP address

Here is the PHP code:

<html>
<head>
 <title>What is my IP address?</title>
</head>
<body>
<?php
 
    if (getenv('HTTP_X_FORWARDED_FOR')) {
        $pipaddress = getenv('HTTP_X_FORWARDED_FOR');
        $ipaddress = getenv('REMOTE_ADDR');
echo "Your Proxy IP address is : ".$pipaddress. "(via $ipaddress)" ;
    } else {
        $ipaddress = getenv('REMOTE_ADDR');
        echo "Your IP address is : $ipaddress";
    }
?>
</body>
</html>

If GEOIP database installed and configured using Apache/Nginx/Lighttpd, try the following php code to get the visitors country name:

   $country = getenv('GEOIP_COUNTRY_NAME');
   echo "Your country : $country";

You can try the demo by visiting this url.

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.