Blog / Cloudflare

Get site user country with Cloudflare IP Geolocation

Are you using Cloudflare as your CDN (Content Delivery Network)? If so, I've got some cool news for you! You can actually use the HTTP_CF_IPCOUNTRY header to detect the country of your users. It's super easy to do and can provide you with some really valuable insights into your user base.

So, here's how it works: every time a request passes through Cloudflare's network, this header is added to it. It contains the two-letter ISO country code of the visitor's country. With this information, you can customize your website or application to better serve users from different countries.

For example, let's say you have a website that sells products online. By detecting the country of your users, you can display prices in their local currency and offer region-specific promotions. This can make your website much more user-friendly and increase the chances of a sale.

If you're using PHP, here's an example of how you can use the HTTP_CF_IPCOUNTRY header to detect the country of your users:

$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];

if ($country_code == "US") {
    // Do something for US visitors
} elseif ($country_code == "GB") {
    // Do something for UK visitors
} else {
    // Do something for visitors from other countries
}

You can also detect the city of your users with Cloudflare, but it requires a different header called HTTP_CF_IPCITY. This header contains the city of the visitor's IP address.

It's important to note that not all IP addresses have associated city data, so this header may not always return a value. Additionally, the accuracy of the city data can vary, depending on the IP geolocation provider Cloudflare uses.

Here's an example of how you can use the "HTTP_CF_IPCITY" header to detect the city of your users in PHP:

$city = $_SERVER["HTTP_CF_IPCITY"];

if (!empty($city)) {
    // Do something with the user's city
} else {
    // The city could not be determined
}