How to Get URL Parameters in Drupal 7

drupal 7 logo

I’ve seen the horror! (allow me some drama here) I’ve seen code in Drupal projects, trying to get parameters from URLs in this way:

$params = $_GET;
or
$some_var = $_GET['some_var']

Drupal has some functions to deal with parameters coming from a URL. Now, let me be honest, it’s not more secure if you use those functions, is just the Drupal way to do it. Having said this, don’t get relaxed thinking that you’re covered by getting your parameters this way, you still have to properly scape them according to what you will do with them.

So, let’s say you have a URL like this https://somecooldomain.com?category=shoes&brand=adidas

You can get the parameters using the Drupal function drupal_get_query_parameters()

$params = drupal_get_query_parameters();
$category = $params['category'];
$brand = $params['brand'];

Something more common in Drupal, is that you use clean URLs, and there’s also a function to get the parameters in that case.

Clean URL: https://somecooldomain.com/shoes/adidas

In an ideal scenario, you should use a callback function in a menu and named arguments. But in case you’re in a really particular scenario and need to get arguments like this, you can do it using the arg() function.

$category = arg(0);
$brand = arg(1);

I’m not covering how to sanitize those strings in this post, but you can take a look at some of the functions you can use for that:

In a later post, I’ll share how to use a callback function to get arguments in a menu (using Drupal hook_menu)