Get the Real-IP address of a visitor on your website
We are going to make use of three environment variables of PHP in order to code this simple PHP class that returns the real IP address of a visitor, even when connecting via a proxy. The three PHP environment variables we`ll use are
HTTP_CLIENT_IP: gets the IP address of Internet Service Provider.
HTTP_X_FORWARDED_FOR: gets the ip if the request is passed from a proxy. It will be empty if the pass is from a proxy.
REMOTE_ADDR: gets the IP address of requesting client.
Now, with all the all the required variables explained let us code our PHP class.
function real_ip_address() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])){ //check if ip is from ISP $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ //check if ip is passed from a proxy $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else{ $ip = $_SERVER['REMOTE_ADDR']; } return $ip; }
Now, the question is how to use this class? Copy the above code and paste it in a text file between the <?php - ?> tags. Save the file as realipaddress.php and place in your document root. Include this php file in your other code files by writing the statement
include('realipaddress.php');
Now you can get the client`s IP address stored in a variable called $ip