Drupal base URL for hard coded images on a local environment

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...

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"  />

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

What I prefer to do is add lines to the OS's hosts file so that e.g. mysite.localhost points at 127.0.0.1 - then you can set up your webserver vhost with a ServerName of mysite.localhost and have your site running from the root. You can have as many of these local host definitions as you want and serve each from their own root.

Post new comment

The content of this field is kept private and will not be shown publicly.

Learn how to write custom Drupal modules

Does Drupal module development make your head explode and drive you crazy?

Why not learn from someone who has paved the way instead?

Sign up to Master Drupal 7 Module Development.

Hello!!

I am Blair Wadman and this is where I write about Drupal, PHP, CSS etc

Stuff

Syndicate

Syndicate content

© Blair Wadman
2005 - 2011