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.