Loading...


Related Products


Date Published: February 5, 2025

Setting CF-IPCountry as a response header via PHP

This guide will show you how to create a simple module to capture the CF-IPCountry header incoming from Cloudflare (https://support.cloudflare.com/hc/en-us/articles/200168236-Configuring-Cloudflare-IP-Geolocation) and set it to the response headers using an Event Subscriber. 

Warning

Drupal page cache does not respect the Vary header, please ensure that you read Drupal 8 page cache does not respect the Vary header

Note Acquia Edge does not respect the "Vary" header !

 

Create a custom module using the following structure replacing cf_header and CfSubscriber with the names of your choice:

Edit the CfSubscriber.php file to contain the below, modifying the namespace and class name appropriately

<?php

namespace Drupal\cf_header\EventSubscriber; #<-- MODIFY THIS

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Class CfSubscriber. <-- MODIFY THIS
 */
class CfSubscriber implements EventSubscriberInterface { #<-- MODIFY THIS

  /**
   * Symfony\Component\HttpFoundation\RequestStack definition.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructs a new CfSubscriber object. <-- MODIFY THIS
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events['kernel.response'] = ['kernelResponse'];

    return $events;
  }

  /**
   * This method is called when the kernel.response is dispatched.
   *
   * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
   *   The dispatched event.
   */
  public function kernelResponse(FilterResponseEvent $event) {
    $request = $this->requestStack->getCurrentRequest();
    $headers = $request->headers->get('CF-IPCountry');
    $response = $event->getResponse();
    $response->headers->set('CF-IPCountry', $headers);

  }

}

Edit cf_header.services.yaml to contain the below, modifying service name and cla name appropriately

services:
  cf_header.default: # <-- MODIFY THIS
    class: Drupal\cf_header\EventSubscriber\CfSubscriber # <-- MODIFY THIS
    arguments: ['@request_stack']
    tags:
      - { name: event_subscriber }

You can now enable the module on your site which will capture the request header and set it to the response.

Did not find what you were looking for?

If this content did not answer your questions, try searching or contacting our support team for further assistance.

Back to Section navigation
Back to Site navigation