I’m proxying my website traffic through Cloudflare and would like to take advantage of their geolocation functionality shown here: https://developers.cloudflare.com/workers/examples/geolocation-hello-world/.
The website is on WordPress and I want to be able to fetch the geolocation using PHP in a plugin. I saw on here that by default you can call the country by using:
$userCountry = $_SERVER["HTTP_CF_IPCOUNTRY"];
But I haven’t found anything that will do the same for the region code. Therefore I’m trying to set up a Cloudflare worker which can pass the result of request.cf.region to the header, so that I can call it like so:
$regionCode = $_SERVER["HTTP_CF_IPREGIONCODE"];
Am I on the right track here? Could someone please give me a pointer on how to achieve what I describe?
2
Answers
You will have to change your approach a bit.
The reason you get the IP country in your headers is that CloudFlare by default adds some predefined values, as seen here.
Since there is no info for the IP region, you will have to add it yourself in the worker code. The snippet that should do the work would look like this:
And then use it in your WordPress code as you described.
Just to inform other visitors, there are several solutions for this issue.
The most famous solution is the worker, which needs configurations. Recently, the Cloudflare added a feature that automatically adds the user’s geolocation information to the request. To set that up, follow the below steps:
Then you can access these meta data from $_SERVER global in PHP, you can use the below variables that was useful for me: