How can I get the client's IP address in a PHP webservice? [duplicate] How can I get the client's IP address in a PHP webservice? [duplicate] php php

How can I get the client's IP address in a PHP webservice? [duplicate]


This should be what you want:

$_SERVER['REMOTE_ADDR']

The IP address from which the user is viewing the current page.

http://php.net/manual/en/reserved.variables.server.php


Actually, I would suggest using this function to cover all of your bases, such as people using proxies, shared networks etc.:

function getUserIpAddr(){    if (!empty($_SERVER['HTTP_CLIENT_IP'])) //if from shared    {        return $_SERVER['HTTP_CLIENT_IP'];    }    else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //if from a proxy    {        return $_SERVER['HTTP_X_FORWARDED_FOR'];    }    else    {        return $_SERVER['REMOTE_ADDR'];    }}


Make sure not to trust data sent from the client. $_SERVER['REMOTE_ADDR'] contains the real IP address of the connecting party. That is the most reliable value you can find.

However, they can be behind a proxy server in which case the proxy may have set the $_SERVER['HTTP_X_FORWARDED_FOR'], but this value is easily spoofed. It can be set by someone without a proxy to whatever value the user wants, or the IP can be an internal IP from the LAN behind the proxy.

This means that if you are going to save the $_SERVER['HTTP_X_FORWARDED_FOR'], make sure you also save the $_SERVER['REMOTE_ADDR'] value, e.g., by saving both values in different fields in your database.

If you are going to save the IP to a database as a string, make sure you have space for at least 45 characters. IPv6 is here to stay and those addresses are larger than the older IPv4 addresses.