How to get client IP using php

Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

How to get client IP using php

Post by Saman » Mon Jul 26, 2010 5:11 pm

Are you using $_SERVER['REMOTE_ADDR'] to find the the client’s IP address in PHP? Well, you might be amazed to know that it may not return the true IP address of the client at all time. If your client is connected to the Internet through Proxy Server then $_SERVER['REMOTE_ADDR'] in PHP just returns the the IP address of the proxy server not of the client’s machine. So here is a simple function in PHP to find the real IP address of the client’s machine. There are extra Server variable which might be available to determine the exact IP address of the client’s machine in PHP, they are HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR.

Function to find real IP address in PHP,

Code: Select all

function getIP(){

    if (!empty($_SERVER['HTTP_CLIENT_IP'])){   //check ip from share internet
      $ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){   //to check ip is pass from proxy
      $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else{
      $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
 
In this PHP function, first attempt is to get the direct IP address of client’s machine, if not available then try for forwarded for IP address using HTTP_X_FORWARDED_FOR. And if this is also not available, then finally get the IP address using REMOTE_ADDR.
Pansophic
Sergeant
Sergeant
Posts: 25
Joined: Sun Feb 13, 2011 4:05 pm

Re: How to get client IP using php

Post by Pansophic » Tue Mar 01, 2011 2:41 pm

hey thanks for this, it really solved my problem, I was looking for something like this from a long time.
Post Reply

Return to “PHP & MySQL”