Find the IP address of your website’s visitors
--
There are dozens of posts on Q & A sites & forums that essentially ask : “How can I find the IP address of my website’s visitor”. The questions have collectively gathered thousands of votes and millions of views.
TL;DR : There are several ways to find the IP address of your client but the answer depends on your setup. Some methods are prone to spoofing.
A very common theme in the answers is trial and error like the if-else block below. Please don’t copy it without understanding what it is doing as it can open your code to dangerous attacks.
The problem with finding the IP address of your client (website visitor) is that the answer depends on your backend server setup. Quite often it can be accessed by reading the REMOTE_ADDR header but it may not always be correct.
Let’s look at some examples in PHP to understand this. $_SERVER is an array of headers created by the web server. Some of the variables that can help us find the IP address of the client are :
REMOTE_ADDR
HTTP_CLIENT_IP
HTTP_COMING_FROM
HTTP_FORWARDED
HTTP_FORWARDED_FOR
HTTP_FROM
HTTP_PROXY_CONNECTION
HTTP_VIA
HTTP_X_COMING_FROM
HTTP_X_FORWARDED
HTTP_X_FORWARDED_FOR
HTTP_X_REAL_IP
The most commonly used headers for finding the IP address of a client in PHP are :
- $_SERVER[‘REMOTE_ADDR’] — This is the IP address from which the request is received by the web server. Depending on your configuration, this may not always be the IP address of your client (e.g. it may be the IP of the proxy sitting just before the web server that intercepts the requests). Here are a few examples:
- $_SERVER[“REMOTE_ADDR”] gives server IP rather than visitor IP
- $_SERVER[‘REMOTE_ADDR’] not giving the right ip address - $_SERVER[‘HTTP_X_FORWARDED_FOR’] — This is a list of IP addresses starting from the original client and including each successive proxy that intercepted the request. Theoretically you can obtain the client’s IP address from this list. Unfortunately, this header can be easily spoofed.
Key points to keep in mind
- Do not blindly trust any data sent from the client
- Avoid copy pasting code samples because the solutions are often specific to a particular backend configuration.
- Some of the solutions might appear to work in your development environment but you should make sure that you aren’t opening a security hole (e.g. Anatomy of an Attack: How I Hacked StackOverflow)
On a side note, if the IP address is only needed on your client side, you can find it by sending a request to ipapi.co/ip from your client. The value returned is the IP address in text format. Both IPv4 and IPv6 clients are supported.