Drupal - How to check if the current page is a 404 error from a module/template?

In Drupal 7, you can use drupal_get_http_header().

In the template.php file, use this code.

$status = drupal_get_http_header("status");
if ($status === '404 Not Found'){
  // Do something.
}

In Drupal 8, you can use the following code in a hook.

$route_name = \Drupal::request()->attributes->get('_route');
if ('system.404' === $route_name) {
  // Do something.
}

Drupal 8.2.x:

Unfortunately, drupal_get_http_header("status") doesn't work any more.

Try:

$status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
if ($status && $status->getStatusCode() == 404){

}

There is a discussion of this here: https://www.drupal.org/node/1969270


This is the simplest way to detect Access Denied (403) and Page Not Found (404) in Drupal 7.

// get the menu router item for the current page
$router_item = menu_get_item();

// if there is no router item, this page is not found
$is_page_not_found_404 = empty($router_item);

// if 'access' is empty for the router item, access is denied
$is_access_denied_403 = empty($router_item['access']);

Tags:

Http Request