How to not tear your hair out finding the current URL in Drupal

It's tricker than it seems to get the URL to the current page you're on in Drupal, and the solution you use depends on what your goal is. Let's explore a couple of options. Let's say the URL to the current page is the following:

http://example.com/user?queryvar=1

Note that I've added a query string to demonstrate how it can complicate things. Let's look at the first option, which probably will work for us most of the time:

request_url();

The request_uri() function is a utility function supplied by Drupal for just this use. Here's what it returns:

/user?queryvar=1

We can go ahead and slip that right into a link, but to manipulate it would take some work. It's not a value we can pass into url() or l() and have work. And if we're not sure if there's going to be a query string, we can't just go and add to it without a check. Let's look at another option:

$_GET['q'];

This $_GET variable typically corresponds directly to the the path that you would pass to a url() or l() function, and in this case it would typically return the following:

user

This is something we can work with, but I've worked with several sites where the $_GET value doesn't necessarily correspond directly to the current page. For example, on the project that spurred this post, $_GET['q'] on /user will return /user/8423, which will return a different url if passed to url(). So, it didn't work for this particular case. The solution I found seems a little twisted, but here it is:

trim($_SERVER["REDIRECT_URL"], '/');

This returns the correct value for me every time, with the query string stripped off. It is an absolute URL, which means that before we trim the slash off of it, $_SERVER["REDIRECT_URL"] would return /user.

Good luck, and I hope you found this before totally blowing a fuse.

Add to playlist

Add to , or

Add to new playlist:

Add to playlist
This is a member-only feature
But, it's easy to become a member

Add to cart:


Loading...
Contact us

Below are the supported keyboard shortcuts for our video player.

space
Start / stop video
shift
Go to next video
shift
Go to previous video
Increase or decrease player speed by 20%
Skip ahead or go back by 15 seconds
1...9
Jump to a percentage (2 is 20%, for example)
f
Toggle full screen
Videos Pricing More Search
BuildAModule Logo Icon BuildAModule Logo Icon
Become a member!
$29
1 month
$156
6 months
10% off
$276
12 months
20% off
All memberships come with the following:
24 / 7 access to the entire 1800+ video library
An innovative video player with a rolling transcript
Extensive Drupal and cross-platform training
A thorough and thoughtful training style
Progress tracking
Take notes on specific video sections
Intuitive multi-user management
How many users?
user
Go solo with a single user, or give multiple team members access through one account and get discounts by bundling multiple users into a single membership.