Search This Blog

Thursday, December 12, 2013

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:
Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsPHP+LAMP
Estimated completion timeN/A

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.

No comments:

Post a Comment