Drupal base URL for hard coded images on a local environment

Images paths are often incorrect when developing/testing a Drupal website on a local machine.
Lets assume images are located in the following folder: sites/all/files. Lets assume that you have hard-coded an image element into a view header. You would use something like this:

<img src="/sites/all/files/myimage.jpg" alt="my alt tag" width="100" height="200"  />

On a live website with a domain name of example.com, the full path for the image will be: example.com/sites/all/files/myimage.jpg. .

If you have a copy of that site running locally, then your site url might be http://localhost/workingcopy/websites/example. As far as your local webserver is concerned, localhost is your root. So i will use the following path for displaying our image: http://localhost/sites/all/files/myimage.jpg, which is incorrect as it is missing "workingcopy/websites/example".

Remedy:

1) in settings.php, set the base url variable.
Example:

$base_url = 'http://localhost/workingcopy/websites/example';

2) In the image element, add the base url variable, as follows:
Example:

<img src="<?php global $base_url; print $base_url;?>/sites/all/files/myimage.jpg" alt="some alt text" width="100" height="200"  />

EDITED 10 AUG 2010: There is an alternative solution on Drupal Coder (as kindly pointed out in one of the comments). I'd recommend checking it out: http://www.drupalcoder.com/story/18-portable-sites-with-base-href-baseur...

Comments

It is not that flexible 'cause if you suddenly decide to move from single-site installation to multi-site you will have the same problem.

Now that's an efficient, time-saving tip. Thanks for the post.

This is definitely not the way to go. Drupal Coder gives a better solution: http://www.drupalcoder.com/story/18-portable-sites-with-base-href-baseur...

Thanks for the link Jeeremie. I will update the post with a link to that as a (better) alternative

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options