0

I want to add a session cookie when a user logs in.

The previous implementation I had, was setting the cookie in hook_user_login with this snippet:

$response = new Response();
$response->headers->setCookie($plain_cookie);
$response->send();

But this was causing randomly the following exception:

RuntimeException: Failed to start the session because headers have already been sent

After some research, I found out that a way to handle it is via an EventSubscriber. https://www.drupal.org/docs/develop/creating-modules/subscribe-to-and-dispatch-events

However, I have not managed to dispatch a ResponseEvent in order to add the cookie to the response header, aka. the cookie is not being added after login. I have tried event low priorities in order for the event to be exeuted at the end, but again it does not work.

function custom_user_login($account) {
  $response = new Response();
  $event = new MyResponseEvent($response);

  $event_dispatcher = \Drupal::service('event_dispatcher');
  $event_dispatcher->dispatch($event, MyResponseEvent::EVENT_NAME);
}

And in my EventSubscriber:

public function onUserLogin(MyResponseEvent $event) {
  $response = $event->getResponse();
  $response->headers->setCookie($plain_cookie);
  $event->setResponse($response);
}

How could I do it?

4

1 Answer 1

0

Finally, since I could not find a way to create an EventSubscriber for the login event, I returned to my initial implementation and tried to fix the problem with the $response->send() command.

It seems that if we just want to modify the response headers (e.g. add some cookies) in the context of a hook where a response is already in place, the proper function to use, instead of $response->send() is:

 $response->sendHeaders();

This works fine, setting the cookies properly to the response and does not trigger the fatal error:

Headers already sent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.