How to learn the client's ip

How to learn the client's ip

Digital Hits: 87

To the IP address of the visitor of your website it is possible to learn about it very much - the country, the city, the name and the email address of Internet service provider, etc. But the main value is that IP can serve as the identifier of the visitor for server scripts. It is described below how it is possible to determine the IP address by means of the PHP language.

It is required to you

Instruction

1. For extraction of the IP address from the headings sent to the server of requests of the browser it is necessary to use the getenv function. She reads the values specified by it from environment variables. The variable with the name REMOTE_ADDR is intended for storage of the IP address of the visitor. However the client can use the proxy server, and in this case the variable will contain its address, and at all not that which is necessary to you. Learn that the web surfer uses intermediate IP, it is possible from the variable of an environment with the name HTTP_VIA. In it through a comma all addresses of the proxy servers involved in a chain are located. Intermediate servers are obliged to place the visitor's address in the variable with the name HTTP_X_FORWARDED_FOR, however it completely depends on settings of a proxy. Means to capture as much as possible opportunities of definition of the IP address, it is necessary to check contents of at least three variables: REMOTE_ADDR, HTTP_X_FORWARDED_FOR also still is desirable for HTTP_CLIENT_IP.

2. It is possible to integrate verification of all three variables in one line of the PHP code, for example, so:
$ipAddr = getenv ('HTTP_CLIENT_IP') or of $ipAddr = getenv ('HTTP_X_FORWARDED_FOR') or of $ipAddr = getenv ('REMOTE_ADDR');
Having received in such a way IP addresses value, it is desirable to clean it from possible distortions and excess characters. For this purpose it is possible to use a regular expression:
$ipAddr = trim (preg_replace ('#^ ([^]+) (. *) ?#', '$1', $ipAddr));

3. It was necessary to integrate both code lines in one function:
function getIP () {

$ipAddr = getenv ('HTTP_CLIENT_IP') or of $ipAddr = getenv ('HTTP_X_FORWARDED_FOR') or of $ipAddr = getenv ('REMOTE_ADDR');

return trim (preg_replace ('#^ ([^]+) (. *) ?#', '$1', $ipAddr));

}

Author: «MirrorInfo» Dream Team

Print