In web development it is common to need to obtain a user’s IP in order to differentiate it from the rest. Thanks to this we can create monitoring, controls and even segmentation of the public that visits us.
In this tutorial I am going to do an analysis of how to get the real IP of a user in PHP. At the end of the tutorial I propose a function that performs this task so that you can add it, if you want, to your library of helpers.
Content
- PHP ways to read the IP of a web visit
- Get the normal IP of a user in PHP
- Read the IP address of a user using Proxy
PHP ways to read the IP of a web visit
In PHP there are several ways to read the IP of a visiting user, each of them has a specific objective and we must know how to differentiate them to choose the best one in each case.
We must take into account the different IPs that a user can have, since each one is owed, and then analyze which PHP function provides us with the solution for each case.
Let’s see the different types of IP that a user can have:
- Real IP of ISP. That is, the user has a normal IP and has accessed our site without intermediate jumps. This IP is the easiest to read in PHP.
- proxy IP. This type of IP occurs when a user visits our site from another in a way that hides their primary IP. This address can be easily read in PHP with a corresponding function.
- Modified IP. This isn’t actually an IP, but can actually be any value (text or numbers) a user wants to enter. I will analyze this type of IP address later, and special care must be taken with its content.
Get the normal IP of a user in PHP
We are going to see, first of all, the basic way to read any traditional IP of a user, it is not infallible, but it is the first method of reading addresses that you should know.
This reading is as simple as accessing the value of the server variable REMOTE_ADDR. This variable belonging to the variable super global $_SERVER always stores the user’s IP.
The code would be simple, an example would be the following:
<?php $ip_usuario = $_SERVER['REMOTE_ADDR']; ?>
Read the IP address of a user using Proxy
Even if our visitor uses a proxy we can read your IP address. For this we will use a server variable different from the previous one, the variable HTTP_X_FORWARDED_FOR.
function getRealIpAddr() { if (!emptyempty($_SERVER['HTTP_CLIENT_IP'])) { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; }