Drupal URL/URI - How to get the URL/URI of the current Drupal page

Drupal FAQ: How do I get the URI (or URL) of the current web page from my Drupal theme?

Sometimes when you're working on a Drupal theme, or customizing an existing Drupal theme, you'll want to know the URL (or more likely, the URI) of the page that the user is currently looking at so you can customize that page (or more likely, a series of pages beginning with a certain URI pattern, as with this Custom Drupal PHP block example).

For instance, when users are authenticated to this website (devdaily.com), I don't show advertisements on many pages. Some of that is controlled through Drupal blocks, but to control other ads, I had to dig into my Drupal theme, and add some logic based on the URI of the current page the user was looking at.

A simple Drupal URL/URI test

My code to get the Drupal URI of the current page looks like this:

$curr_uri = check_plain(request_uri());

Note that you can get the Drupal URI without using the check_plain method, like this:

$curr_uri = request_uri();

but I like the fact that the check_plain method makes sure the URI is properly encoded. This is good from a security perspective, as I've seen some hackers hit my websites with some crazy-looking URLs.

What I mean by Drupal URI (versus "URL")

If you're not familiar with the term "URI", what I mean is the part of the URL that comes after the domain name. For instance, if you have a URL that looks like this:

http://www.devdaily.com/drupal/theme-test-drupal-user-logged-in-authenticated

the URI portion of that Drupal URL is this:

/drupal/theme-test-drupal-user-logged-in-authenticated

This string is what you get from the Drupal request_uri method. Most people are familiar with the term "URL", but they may not be familiar with the term "URI".

Once you have the URI of the current Drupal page in your variable, you can make whatever decisions you need to make using that variable.

Put the logic in a module

Warning: If you put too much code like this into your Drupal theme pages, they will soon get out of control, so it's recommended that you move code like this to methods in your theme's template.php file. I'll cover that in more detail in a future Drupal tutorial.

PHP Drupal URL/URI reference

There is a nice Drupal URI discussion on this Drupal support forum page.

This code was tested using Drupal 6.x.

Comments