1

This question already has an answer here:

Consider this simple implementation of hook_menu()

/**
 * Implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'title' => 'Hello world!',
    'page callback' => 'helloworld_page',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Page callback for /hello.
 */
function helloworld_page() {
  return "Hello World!";
}

This code work when I visit example.com/hello, but so does when I append extra argument to the url like example.com/hello/world. How do I only define the example.com/hello only without getting all these 'derivative' URL defined as well?

marked as duplicate by Clive 7 Jul 22 '16 at 8:05

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3

Per the hook_menu() docs:

When path 'abc/def' is requested, no further path components are in the request, and no additional arguments are passed to the callback function (so $ghi and $jkl would take the default values as defined in the function signature). When 'abc/def/123/foo' is requested, $ghi will be '123' and $jkl will be 'foo'. Note that this automatic passing of optional path arguments applies only to page and theme callback functions.

In other words, it's a feature of the Drupal menu routing system to accept additional path components.

If you're looking to try to circumvent this, you can use an access callback function to enforce your sole path:

/**
 * implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'title' => 'Hello world!',
    'page callback' => 'helloworld_page',
    'access callback' => 'helloworld_callback',
  );

  return $items;
}

/**
 * Page callback for /hello.
 */
function helloworld_page() {
  return "Hello World!";
}

/**
 * Access callback for /hello. 403 on addition path components.
 */
function helloworld_callback() {
  return (request_path() == 'hello');
}
  • 3
    Being pedantic, it'd be more accurate to serve a 404 here - since the URI isn't supposed to exist, a 403 isn't technically the right response. That can be accomplished in various ways in the page callback itself by checking func_get_args() or the request_path() and simply using return MENU_NOT_FOUND; or adding drupal_not_found() when the condition matches – Clive Jul 22 '16 at 8:16

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