How To Find Out The Client's Ip

Table of contents:

How To Find Out The Client's Ip
How To Find Out The Client's Ip

Video: How To Find Out The Client's Ip

Video: How To Find Out The Client's Ip
Video: How to detect and get user or client's IP address with PHP 2024, April
Anonim

By the IP address of a visitor to your site, you can find out quite a lot about him - country, city, name and email address of the Internet provider, etc. But the main value is that the IP can serve as a visitor ID for server-side scripts. Below is described how you can determine the IP address using PHP language.

How to find out the client's ip
How to find out the client's ip

It is necessary

Basic knowledge of PHP

Instructions

Step 1

To extract the IP address from the headers sent to the browser request server, use the getenv function. It reads the values specified to it from the environment variables. A variable named REMOTE_ADDR is used to store the visitor's IP address. However, the client can use a proxy server, in which case the variable will contain its address, and not the one you want. You can find out that the web surfer is using an intermediate IP by looking at the environment variable called HTTP_VIA. All addresses of the proxy servers involved in the chain are placed in it, separated by commas. Intermediate servers must place the visitor's address in a variable named HTTP_X_FORWARDED_FOR, but this depends entirely on the proxy settings. This means that in order to cover as many possibilities of determining the IP address as possible, you need to check the contents of at least three variables: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, and preferably

Step 2

You can combine checking all three variables into one line of PHP code, for example, like this:

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

Having obtained the value of the IP address in this way, it is advisable to clear it from possible distortions and unnecessary characters. You can use a regular expression for this:

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

Step 3

It remains to combine both lines of code into one function:

function getIP () {

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

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

}

Recommended: