Skip to main content
3 of 4
added 1090 characters in body
avpaderno
  • 97.9k
  • 15
  • 164
  • 284

What is wrong with your code is that the code that outputs the content of the block needs to be executed, such as:

$block['content'] = test_get_block_content();

This code makes sense if the code needs to output something in the page; if the code that needs to be executed doesn't need to output anything in the page, then hook_exit() is always executed, even on cached pages. The documentation for that hook reports the following text:

Only use this hook if your code must run even for cached page views. If you have code which must run once on all non cached pages, use hook_init() instead.

As for redirecting a user, you can look at what the Redirect module does to redirect a user. The purpose of the module is to redirect a user basing on the currently visited page, and on settings decided from an administrator user. The code that redirects the user is contained in this function, which is the implementation of hook_init():

/**
 * Implements hook_init().
 */
function redirect_init() {
  if (!redirect_can_redirect()) {
    return;
  }

  $current_path = current_path();
  $current_langcode = $GLOBALS['language']->language;
  $current_query = drupal_get_query_parameters();
  if ($redirect = redirect_load_by_source($current_path, $current_langcode, $current_query)) {
    redirect_redirect($redirect);
  }
  // …
}

If you would implement a way to redirect a user through drupal_goto(), you should consider implementing hook_init() too.

avpaderno
  • 97.9k
  • 15
  • 164
  • 284