Basically the issue is that drupal_set_message() shows a message twice on some pages, when it is called from hook_init().

How can I avoid it happens?

2 Answers 2


It's likely that the first message you see is the left-over result of a previous AJAX call, and the second message is the one you're intending to see.

To test that, open a different browser and browse to the page in question. First time round you should see the message once; when you refresh the page, and on subsequent requests, you should see it twice.

It happens because hook_init() is also invoked for AJAX requests, but the messages added to the session are never printed-then-cleared - so there's an extra copy of the same message in the next normal page load.

For most (all?) modern browser/server combinations you can use something like this to detect whether or not the request is from an AJAX source, and react accordingly:

function is_ajax_request() {
  return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
  • hi Clive, thanks for the answer! So according to you if I add this in the check in hook_init - it must work, but I just checked and it is not working so here is what I wrote in hook_init: if (user_is_logged_in() && !_is_ajax_request() && !have_profile()) { drupal_set_message(...) } Nov 5, 2013 at 14:22
  • Is have_profile() returning the expected value?
    – Clive
    Nov 5, 2013 at 14:27
  • yes I was just editing my comment ... exactly Nov 5, 2013 at 14:27
  • yes ... everything is working - just it is showing twice sometimes, and when I checked further - I realized that the hook_init is executing twice, because I added a dpm there Nov 5, 2013 at 14:28
  • Hmmm...you can check that it's the definitely happening twice in the same request using a static: static $foo = FALSE; if (!$foo) { $foo = TRUE; drupal_set_message('..); }. If you only get one message from now on, then hook_init() is indeed being invoked twice. If not, it's that the message is being added to the session as part of another page request somehow (and usually that's AJAX)
    – Clive
    Nov 5, 2013 at 14:33

The easiest way to avoid the messages are repeated is setting the drupal_set_message() $repeat parameter to FALSE.

 drupal_set_message(t('You must validate your email address for this account before logging in via OpenID.'), 'status', FALSE);

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.