Get real ip address php

I'm using this PHP code to get a visitor's IP address:


But, I can't get the real IP address from visitors when they are using a proxy. Is there any way to get a visitor's IP address in this case?

reformed

4,24510 gold badges59 silver badges83 bronze badges

asked Nov 30, 2012 at 13:58

4

Try this php code.


Mario

1,2943 gold badges20 silver badges39 bronze badges

answered Nov 30, 2012 at 14:01

10

This is the most common technique I've seen:

function getUserIP() {
    if( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')>0) {
            $addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']);
            return trim($addr[0]);
        } else {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

Note that it does not guarantee it you will get always the correct user IP because there are many ways to hide it.

answered Nov 30, 2012 at 14:08

TeneffTeneff

27.8k9 gold badges64 silver badges96 bronze badges

4

This is my approach:

 function getRealUserIp(){
    switch(true){
      case (!empty($_SERVER['HTTP_X_REAL_IP'])) : return $_SERVER['HTTP_X_REAL_IP'];
      case (!empty($_SERVER['HTTP_CLIENT_IP'])) : return $_SERVER['HTTP_CLIENT_IP'];
      case (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) : return $_SERVER['HTTP_X_FORWARDED_FOR'];
      default : return $_SERVER['REMOTE_ADDR'];
    }
 }

How to use:

$ip = getRealUserIp();

answered Mar 3, 2015 at 23:36

El ceroEl cero

5694 silver badges13 bronze badges

7

Proxies may send a HTTP_X_FORWARDED_FOR header but even that is optional.

Also keep in mind that visitors may share IP addresses; University networks, large companies and third-world/low-budget ISPs tend to share IPs over many users.

answered Nov 30, 2012 at 13:59

Get real ip address php

HalcyonHalcyon

56.6k10 gold badges87 silver badges126 bronze badges

2

apply this code for get the ipaddress:

    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"; }
    ------------------------------------------------------------------------

Get real ip address php

Arpit Patel

9,2155 gold badges63 silver badges72 bronze badges

answered Feb 22, 2016 at 8:51

This is my function.

benefits :

  • Work if $_SERVER was not available.
  • Filter private and/or reserved IPs;
  • Process all forwarded IPs in X_FORWARDED_FOR
  • Compatible with CloudFlare
  • Can set a default if no valid IP found!
  • Short & Simple !

/**
 * Get real user ip
 *
 * Usage sample:
 * GetRealUserIp();
 * GetRealUserIp('ERROR',FILTER_FLAG_NO_RES_RANGE);
 * 
 * @param string $default default return value if no valid ip found
 * @param int    $filter_options filter options. default is FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
 *
 * @return string real user ip
 */

function GetRealUserIp($default = NULL, $filter_options = 12582912) {
    $HTTP_X_FORWARDED_FOR = isset($_SERVER)? $_SERVER["HTTP_X_FORWARDED_FOR"]:getenv('HTTP_X_FORWARDED_FOR');
    $HTTP_CLIENT_IP = isset($_SERVER)?$_SERVER["HTTP_CLIENT_IP"]:getenv('HTTP_CLIENT_IP');
    $HTTP_CF_CONNECTING_IP = isset($_SERVER)?$_SERVER["HTTP_CF_CONNECTING_IP"]:getenv('HTTP_CF_CONNECTING_IP');
    $REMOTE_ADDR = isset($_SERVER)?$_SERVER["REMOTE_ADDR"]:getenv('REMOTE_ADDR');

    $all_ips = explode(",", "$HTTP_X_FORWARDED_FOR,$HTTP_CLIENT_IP,$HTTP_CF_CONNECTING_IP,$REMOTE_ADDR");
    foreach ($all_ips as $ip) {
        if ($ip = filter_var($ip, FILTER_VALIDATE_IP, $filter_options))
            break;
    }
    return $ip?$ip:$default;
}

answered May 2, 2017 at 12:47

If the Proxy is which you trust, you can try: (Assume the Proxy IP is 151.101.2.10)

 $header) {

        if (isset($_SERVER[$header]) && filter_var($_SERVER[$header], FILTER_VALIDATE_IP)) {

            $clientIP = $_SERVER[$header];

            break;
        }
    }
}

echo $clientIP;

This will prevent forged forward header by direct requested clients, and get real IP via trusted Proxies.

answered Jul 8, 2017 at 2:15

Nick TsaiNick Tsai

3,51731 silver badges34 bronze badges

Yes, $_SERVER["HTTP_X_FORWARDED_FOR"] is how I see my ip when under a proxy on my nginx server.

But your best bet is to run phpinfo() on a page requested from under a proxy so you can look at all the availabe variables and see what is the one that carries your real ip.

answered Nov 30, 2012 at 14:03

NelsonNelson

47.4k8 gold badges64 silver badges79 bronze badges

This works for Windows and Linux! It doesn't matter if it's localhost or online..

    function getIP() {
    $ip = $_SERVER['SERVER_ADDR'];

    if (PHP_OS == 'WINNT'){
        $ip = getHostByName(getHostName());
    }

    if (PHP_OS == 'Linux'){
        $command="/sbin/ifconfig";
        exec($command, $output);
        // var_dump($output);
        $pattern = '/inet addr:?([^ ]+)/';

        $ip = array();
        foreach ($output as $key => $subject) {
            $result = preg_match_all($pattern, $subject, $subpattern);
            if ($result == 1) {
                if ($subpattern[1][0] != "127.0.0.1")
                $ip = $subpattern[1][0];
            }
        //var_dump($subpattern);
        }
    }
    return $ip;
}

answered Nov 17, 2015 at 13:45

ValconeValcone

592 silver badges14 bronze badges

5

How can I get a real IP address?

Find your IP address using the command prompt (CMD).
Open the Start menu and type cmd to open the Command Prompt..
Type ipconfig into the Command Prompt and press Enter. The tool will return a set of data that includes your IP address..

How can I get IP address in PHP?

Using getenv() function: To get the IP Address,we use getenv(“REMOTE_ADDR”) command. The getenv() function in PHP is used for retrieval of values of an environment variable in PHP. It is used to return the value of a specific environment variable.

How can I get static IP in PHP?

In order to obtain the IP address of the server one can use ['SERVER_ADDR'], it returns the IP address of the server under the current script is executing. Another method is using the ['REMOTE_ADDR'] in the $_SERVER array.

What is $_ server [' Remote_addr ']?

$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page. $_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the current page. $_SERVER['REMOTE_PORT']