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-baseurl-in-drupal

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:

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

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

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

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

If you liked this, you'll love my book, Master Drupal Module Development.

"..the must have drupal developers book"


Feeling stuck with Drupal 8 module dev?

Get the free 7 lesson course that will help you get started today without feeling overwhelmed.

  • Create Drupal modules with just a few commands using the Drupal Console
  • Create custom pages
  • Create custom blocks
  • Create admin forms
  • Demystify routers and controllers
  • Bonus material

Find out more


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

Blair Wadman's picture

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.

Add new comment