How to Set header in Drupal 8

 Drupal 8 has introduced symfony request reponse object. So anything related to request/response header or body level changes should be using these new system instead of procedural functions like drupal_add_http_header, drupal_send_headers, drupal_page_header.


Drupal 7

function drupal_serve_page_from_cache(stdClass $cache) {

...

...

  // Send the remaining headers.

  foreach ($cache->data['headers'] as $name => $value) {

    drupal_add_http_header($name, $value);

  }


}


Drupal 8

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\HttpFoundation\Response;

function drupal_serve_page_from_cache(stdClass $cache, Response $response, Request $request) {

...

...

  // Send the remaining headers.

    $response->headers->set($name, $value);

 }


}


Drupal 7

drupal_add_http_header();

Drupal 8 

/** @var \Symfony\Component\HttpFoundation\Response $response */

$response->headers->set();


Drupal 7 

drupal_send_headers();


Drupal 8

/** @var \Symfony\Component\HttpFoundation\Response $response */

$response->sendHeaders();


Drupal 7

drupal_page_header();

Drupal 8

/** @var \Symfony\Component\HttpFoundation\Response $response */

$response->sendHeaders();


D7,

<?php drupal_add_http_header('Content-Type', 'text/csv'); ?>


equivalent, in Drupal 8:


<?php 

use Symfony\Component\HttpFoundation\Response;

$response = new Response();

$response->headers->set('Content-Type', 'text/csv');

 ?>


If you want to modify the headers of a response, you need to use an EventSubscriber. Symphony doesn't have a hook system, but instead uses an event/emitter system. Since it's Symphony driving the request/response cycle, you basically needs to integrate with Symphony to do this.

You could take a look at \Drupal\Core\EventSubscriber\FinishResponseSubscriber to see how this is done, the gist of it is this:

/**

 * Add custom headers.

 */

class HeaderResponseSubscriber implements EventSubscriberInterface {

  public function onRespond(FilterResponseEvent $event) {

    $response = $event->getResponse();

    $response->headers->set('Some-Header', 'some value'); 

  }


  public static function getSubscribedEvents() {

    $events[KernelEvents::RESPONSE][] = array('onRespond');

    return $events;

  }

}

Note in the above code all use statements have been excluded, also you need to register your class as a event_subscriber service, this is done in your module's module_name.services.yml file like this:

services:

  name_of_service:

    class: Drupal\Full\Namespaced\Path\To\Class

    tags:

      - { name: event_subscriber }

You can add arguments (other services) that your class will depend on in the services file like normally.

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...