Posted in CDN NodeJS PHP & MySQL Python Server

How to Get Country Code with PHP/Python Flask/NodeJS using Cloudflare IP Geolocation.

How to Get Country Code with PHP/Python Flask/NodeJS using Cloudflare IP Geolocation. Posted on May 9, 2020Leave a comment
I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

Knowing the location of your visitor is very important to analyze your traffic and for security purposes. You need a database to be installed about IPs in your server or you need to access an API service to know the location from IP. But by using Cloudflare, you can get Geolocation header on your server without any database or API. You need to enable Cloudflare on your website first. It will increase your website content delivery speed.

When you enable Cloudflare with your website, be sure you have turned on “Account Panel > Network > IP Geo-location” feature on your Cloudflare panel.

ip geo location

Now you can get the Country code by PHP using following code:

<?php 
    if(isset($_SERVER["HTTP_CF_IPCOUNTRY"])){
        $countrycode = $_SERVER["HTTP_CF_IPCOUNTRY"];
    }else{
        $countrycode = "Not found";
    }
    
    echo $countrycode; 
    //output is "NP" becuase I'm accessing from Nepal
?>

Python using Flask web framework:

country_code = request.headers.get('cf-ipcountry')

NodeJS:

const country_code = headers['cf-ipcountry'];

In this way you can get country code of visitors location without using any database or API.

I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

Leave a Reply

Your email address will not be published. Required fields are marked *