How To Find Out The Ip Of A Site Visitor

Table of contents:

How To Find Out The Ip Of A Site Visitor
How To Find Out The Ip Of A Site Visitor

Video: How To Find Out The Ip Of A Site Visitor

Video: How To Find Out The Ip Of A Site Visitor
Video: How To Know The People Visiting Your Site, Country, IP Address And Browser 2024, May
Anonim

Most often, the IP address of a site visitor is used to identify him. But besides this, using IP, you can get a lot of additional information about the visitor - for example, find out his Internet provider and geographic location. In practice, server-side PHP scripts are most often used to extract IP addresses from the request headers sent by the browser.

How to find out the ip of a site visitor
How to find out the ip of a site visitor

It is necessary

Basic knowledge of PHP

Instructions

Step 1

Use PHP's built-in getenv function to read IP addresses from the superglobal environment variable array. In the simplest case, it will be enough to read the variable named REMOTE_ADDR. The corresponding piece of PHP code might look like this: $ userIP = getenv ('REMOTE_ADDR');

Step 2

In addition to the REMOTE_ADDR variable sent in the request, check the HTTP_VIA and HTTP_X_FORWARDED_FOR variables. If the visitor uses a proxy server, then the intermediate address must be recorded in both variables - in both HTTP_VIA and REMOTE_ADDR. In this case, you can try to find out the real IP of the visitor through HTTP_X_FORWARDED_FOR - the proxy server must put the original address into it. However, this is not always done, and the user has the opportunity to select an "opaque" proxy server that does not transmit the original IP of the visitor who sent the request. In any case, you should use as many ways as possible to get the original IP address in your code by adding a check for the HTTP_CLIENT_IP variable.

Step 3

Concatenate in one line of PHP code sequential validation of three environment variables, which may contain the original IP address of the visitor. This can be done, for example, like this: $ userIP = getenv ('HTTP_CLIENT_IP') OR $ userIP = getenv ('HTTP_X_FORWARDED_FOR') OR $ userIP = getenv ('REMOTE_ADDR');

Step 4

Remove extra characters and other "garbage" from the resulting IP value that may get into environment variables. This can be done, for example, using the built-in PHP functions TRIM and preg_replace: $ userIP = TRIM (preg_replace ('# ^ ([^,] +) (,. *)? #', '$ 1', $ userIP));

Step 5

Combine all the code into a custom function so that you can refer to it instead of repeating the check and cleanup lines over and over in different parts of your PHP scripts. For example, like this: FUNCTION getUserIP () {

$ userIP = getenv ('HTTP_CLIENT_IP') OR $ userIP = getenv ('HTTP_X_FORWARDED_FOR') OR $ userIP = getenv ('REMOTE_ADDR');

RETURN TRIM (preg_replace ('# ^ ([^,] +) (,. *)? #', '$ 1', $ userIP));

}

Recommended: