I can programmatically set a cookie in a Drupal 9 controller and I can see that cookie in Chrome's developer tools. However, I cannot programmatically get that cookie from a hook.

I'm using the SAML Service Provider module. I'm extending the SamlSPDrupalLoginController::initiate() function with this code to set a cookie.

setcookie('stv_saml_idp_id', $idp->get('id'), time() + 86400, '/');

That seems to work fine as I can see the cookie in the Chrome developer tools. Unfortunately, when I attempt to get the cookie back with the following code, I get no results.

function mymodule_saml_sp_drupal_login_user_attributes_alter($user, array $attributes) {
  // …
  $cookies = \Drupal::requestStack()->getCurrentRequest()->cookies;
  $idp_id = $cookies->get('stv_saml_idp_id');

However, if (as a test) I embed the same code in a Basic page, I can get the cookie.

I have also tried with $idp_id = $_COOKIE['stv_saml_idp_id']; but I still could not get the cookie.

How can I read a cookie I programmatically set?

  • What are the cookie attributes in fact in the browser?
    – mona lisa
    Sep 17, 2023 at 4:52
  • Related: is the browser sending that cookie in subsequent requests?
    – mona lisa
    Sep 17, 2023 at 10:09

1 Answer 1


Oh... thanks cilefen. That was a good question that helped me find the problem :-)

I was writing down the attributes to post in reply when I realised my cookie domain differed from the Drupal session cookie domain by 1 character. My cookie domain was:


Whereas, the session cookie had leading dot like so:


So, the solution was to explicitly set the cookie Domain exactly the same as the Drupal session Domain:

setcookie('stv_saml_idp_id', $idp->get('id'), time() + 86400, '/', '.mysub.domain.com');

Thanks again.

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.