IP (Internet Protocol) address is a numerical label that lets you identify your device in a network. That’s what our devices use to identify themselves on the internet. And that’s what we can use to get some information regarding our users, for example, their location. So in this article, I would like to share how to get the user’s IP address in PHP.
If you are here just for the code, it is perfectly fine. You can find it in the first section. But I would highly recommend going through the rest of the article to understand better what the code does as I try to go into detail about it. Or, if you don’t have time to do that now, bookmark the blog post to return to it later. All developers copy code, but what distinguishes great developers from everybody else is that they understand what they copy.
TL;DR and the code
Be attentive if you are using Cloudflare, the algorithm will be a little different
In case you are using Cloudflare:
function get_user_ip(): string
{
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
return $_SERVER["HTTP_CF_CONNECTING_IP"];
}
if (isset($_SERVER['REMOTE_ADDR'])) {
return $_SERVER["REMOTE_ADDR"];
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return $_SERVER["HTTP_X_FORWARDED_FOR"];
}
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER["HTTP_CLIENT_IP"];
}
return '';
}
In case you are not using Cloudflare:
function get_user_ip(): string
{
if (isset($_SERVER['REMOTE_ADDR'])) {
return $_SERVER["REMOTE_ADDR"];
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return $_SERVER["HTTP_X_FORWARDED_FOR"];
}
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER["HTTP_CLIENT_IP"];
}
return '';
}
So, here is the code. Now, if you would like to go, you actually can. But I would like to encourage you to stay and try to understand what you just copied.
What does the code do?
If you are using Cloudflare, we need to check for the HTTP_CF_CONNECTING_IP header in the super global $_SERVER variable. That’s an HTTP Header that Cloudflare will add to the request to your website. The REMOTE_ADDR
header won’t hold what you think it should. Because Cloudflare acts as a reverse proxy and when a request comes to your server, it is a request from Cloudflare, not an actual user. REMOTE_ADDR
header will work, but it will contain the IP address of a Cloudflare server, which is most certainly useless to you.
If you are not using Cloudflare or any other reverse proxy services, you have a few ways to get the user’s IP address. Given that all of them come from the request headers, in PHP, we retrieve them using super global $_SERVER
variable
The best way: $_SERVER[‘REMOTE_ADDR’]. It is the best way because it is the only one that can be trusted to be accurate. Because it is set from TCP connection information, it cannot be spoofed (replaced with malicious intent). But as with all good things, it doesn’t always work.