skip to Main Content

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


  1. 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:

    request.headers.set("X-Header-Name", request.cf.region)
    

    And then use it in your WordPress code as you described.

    Login or Signup to reply.
  2. 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:

    • Go the the Cloudflare dashboard
    • Select a domain
    • Go to the Rules -> Transform Rules -> Managed Transform
    • Enable the Add visitor location headers

    Then you can access these meta data from $_SERVER global in PHP, you can use the below variables that was useful for me:

    [REMOTE_ADDR] => ****
    [HTTP_CF_IPLONGITUDE] => ****
    [HTTP_CF_IPLATITUDE] => ****
    [HTTP_CF_IPCOUNTRY] => ****
    [HTTP_CF_IPCONTINENT] => ****
    [HTTP_CF_IPCITY] => ****
    [HTTP_CF_CONNECTING_IP] => ****
    [HTTP_USER_AGENT] => ****
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search