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.

Image for post
Image for post
Warning ! Do NOT copy this blindly

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 :

Key points to keep in mind

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.

Written by

IP Lookup | IP Geolocation API | IP Address Locator by Kloudend, Inc. USA. Trusted by Fortune 500 !

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store