How To Get The Absolute URL Path, Absolutely, In Drupal

Managing web systems, providing developer support and developing web applications myself, I have come across a lot of programmers that like to use relative paths in their web sites.

This was ok back in the day of the static site, where all your edits were done directly on your production server. However, with todays dynamically generated web application frameworks (I refuse to call them simply CMS's), using relative paths can be a big problem, especially when you are moving your app to different locations to test or preview.

In this post, I am going to explain one way to use absolute paths in Drupal, without requiring you to manually update the paths when you move from environment to environment.

Use the url() function

In my development environment, I do not create a new web server or vhost for each project. Instead, I use my standard document root and create a sub-directory for my project (e.g. /web/www.foo-town.com). When using relative paths in most dynamic web applications, let's say wesetup 'node/101',  hovering over your link produces http://localhost/node/101. This is not what we want, we want http://localhost/www.foo-town.com/node/101. So, we can get this by using Drupals url() function, along with grabbing the environment variable for the server name:

<?php print "http://" . $_SERVER['HTTP_HOST'] . url(); ?>

This will print the correct string. However, it does not print the URI! If you need the URI, then you can use this version:

<?php print "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>

You may also want to make life easier for yourself and create shortcuts to these formats in your template.php file, so you can call them as helper variables throughout your theme. You can do this by adding it to hook_preprocess() in template.php in your theme. If you don't see this function, you'll need to create it:

function hook_preprocess(&$vars){
    $vars['images'] = "http://" . $_SERVER['HTTP_HOST .
    url( $vars['directory'] ) . "/images";

    $vars['theme'] = "http://" . $_SERVER['HTTP_HOST']
    . url( $vars['directory'] );

    $vars['url'] = "http://" . $_SERVER['HTTP_HOST'] .
    url();

    $vars['uri'] = "http://" . $_SERVER['HTTP_HOST'] .
    $_SERVER['REQUEST_URI'];
}

Note that in the example above, I am also calling Drupals 'directory' to translate the current theme directory path. This way, I am able to create shortcuts to my images directory and theme directory itself.

If this did not work for you, keep in mind you need to replace the term hook in hook_preprocess() the example above to the name of your theme!

Once done, you can call these helpers from any where in your theme, but not from inside the CMS editor, when in PHP mode! So beware...