This is a PHP tutorial on how to retrieve a visitor’s country code from Cloudflare’s CF-IPCountry header. Note that this header will only be available if you have enabled the “Cloudflare IP Geolocation” option in the Cloudflare dashboard.
In certain cases, you might want to limit your content to certain countries. Likewise, you might want to show extra content to visitors if they come from a specific country.
Thankfully, this is pretty easy to do if you have Cloudflare enabled.
PHP and the CF-IPCountry header.
The CF-IPCountry header can accessed via the $_SERVER superglobals array like so.
$userCountry = false; //Check to see if HTTP_CF_IPCOUNTRY exists if(isset($_SERVER["HTTP_CF_IPCOUNTRY"])){ //If it is exists, use it. $userCountry = $_SERVER["HTTP_CF_IPCOUNTRY"]; }
In PHP, this header will be named as HTTP_CF_IPCOUNTRY in the $_SERVER array. This will give you the country code of the IP address that the visitor in question is using.
Note how we check to see if it exists before we attempt to use it.
This is important, as your application should not rely on this header. There should always be a fallback. If you disable Cloudflare or stop using it altogether, this header will not exist.
And if you attempt to reference a header that does not exist, your PHP script will generate an undefined index warning.
Basically, your app should be able to handle requests that do not contain the HTTP_CF_IPCOUNTRY header.
This header will give you the country of the user in an ISO 3166-1 Alpha 2 format. As a result, you should not be expecting the full country name of the visitor. i.e. Instead of “United States”, it will return “US”. And instead of “the Netherlands”, it will return “NL”.
There are plenty of PHP libraries out there that will convert these country codes into their full-name format, so be sure to take a look around.
CF-IPCountry Spoofing.
It is extremely important to note that this header can be spoofed if you do not validate that the request is coming from Cloudflare. In other words, a user can manually set this header before connecting directly to your web server.
If they do that, they will be able to fool your PHP application into thinking that they are from a different country.
If this is a major worry for you, then you should check out the “CF-Connecting-IP spoofing” section that we wrote in the article: PHP: Get The Correct IP Address From A Cloudflare Request.