简体   繁体   中英

php, get client ip address

I have two php files in a same directory of a server ( http://www.xxxx.com/php/ ),

1)

$address['http_client'] = $_SERVER['HTTP_CLIENT_IP'];
    $address['http_x_forwarded_for'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
    $address['http_x_forwarded'] = $_SERVER['HTTP_X_FORWARDED'];
    $address['http_forwarded_for'] = $_SERVER['HTTP_FORWARDED_FOR'];
    $address['http_forwarded'] = $_SERVER['HTTP_FORWARDED'];
    $address['remote_addr'] = $_SERVER['REMOTE_ADDR'];

    header('Content-Type: application/json');
    echo json_encode($address);

2)

$json_url = $_SERVER['SERVER_NAME'] . '/php/write_json.php';

    $json_string = '';
    $ch = curl_init($json_url);


    $options = array(CURLOPT_RETURNTRANSFER => true, 
                         CURLOPT_HTTPHEADER => array('Content-type: application/json'), 
                         CURLOPT_POSTFIELDS => $json_string);

    curl_setopt_array($ch, $options);

    $json_string =  curl_exec($ch);
    echo $json_string;

calls 调用

if we suppose the client IP is : and the server one is : ,服务器IP是:
when I call http://www.xxxx.com/php/get_ip.php on a client browser

It shows me the Server IP not the client IP like this :

{
    http_client: null,
    http_x_forwarded_for: null,
    http_x_forwarded: null,
    http_forwarded_for: null,
    http_forwarded: null,
    remote_addr: "80.59.3.23"
}

How can I get the client IP instead of the server one ?

You are calling write_json via curl from the server... that is, the server is actually requesting the write_json file, so write_json is seeing the request come from the server. Why not just use an include rather than a curl call?

Not possible this way. You need to get the client ip first then send it as posted data to server via curl.

Trying to get client IP use following function that will return client IP

// Function to get the client IP address
function get_client_ip() {
    $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;
}

After getting IP in a variable then send

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM