How to Validate Paths in Drupal 7

Submitted by Perignon on Tue, 01/26/2016 - 03:03

TL;DR is that it takes using two API functions to validate a path.

The task of verifying a path is right is a job that any Drupal developer may one day face as a developer. Drupal has a wonderful API, and there are so many things it can without writing much code. Validating a path is not one of those things. At first glance, confirming a path seems to be a simple task. This problem was recently faced working on the Facebook Tracking Pixel module that can track based on paths. For this, we wanted to validate the paths supplied by the user.

There are two tables at play in Drupal that provides the system for handling paths: menu_router and url_alias. The menu_router table is the last step in the routing of a path and contains much information. Modules populate menu_router by executing a hook_menu() call. However, Drupal also allows for URL aliases; this is where the url_alias table comes into play. This table may provide an alias to a menu router.

Coding must check to see if the path supplied by the user is either a valid menu_router item or a valid url_alias. Thankfully no SQL is not required to accomplish this. As always with Drupal, there are multiple ways to accomplish a task. To check the menu_router table you use the function drupal_valid_path(), it is possible to also use menu_get_item() or drupal_get_path_alias() but both functions call drupal_valid_path() to do the heavy lifting. Simultaneously, the code must also check if the path is an alias if it is not a menu router item. To do so, use drupal_lookup_path() to determine if the path is an alias and a valid one.

  if(!(drupal_lookup_path('source', $path) || drupal_valid_path($path))){
    form_set_error('your_form_item', t('The path you have entered (:path) does not appear to be a valid path.', [':path' => $path]));
  }

An Example of Use

Using these two validation functions covers the gamut of URLs that a Drupal site may have. These functions cover nodes, taxonomy, panels, views, and all other possible content.