tags:

views:

29

answers:

2

I have a problem with links testing locally using Apache with Windows. The final links have the following format:

file:///C:/Documents and Settings/USUARIO/My Documents/xampp/htdocs/my_website/images/january/my_image.jpg

The images do not show. However, if I directly copy the src from the img tag and paste it into the browser (Firefox), the image shows up.

I generate the links using the following code:

I define the images directory using:

define(IMAGE_DIR, dirname(__FILE__).'/images/');

Then I use the following to format the path,

$imgPath = IMAGE_DIR.$month.$img;

if($localServer)
{
   $imgPath = str_replace('/','\\', $imgPath);
   $imgPath = 'file:///'.$imgPath;
}

What I'm I doing wrong?

+2  A: 

You are generating image sources that use file:// URLs in a page that was loaded from a web server. File URLs instruct the browser to load a file directly from the disk without making a request to the web server. For security reasons, Firefox and other browsers don't allow pages served by a web server to reference local files, so don't show the images. People accessing your site remotely won't be able to access the files either because the image source would be a reference to a path on their computer.

To get the images to appear, you'll need to change your image sources to refer to locations on a web server, for example images/january/my_image.jpg or /images/january/my_image.jpg.

images/january/my_image.jpg will be interpreted by the web browser relative to the page being requested. For example, if the image appears on the page at http://localhost/page1.php, then the browser will request http://localhost/images/january/my_image.jpg. However, if the image is used on a page at http://localhost/subdir/page1.php, the browser will request http://localhost/subdir/images/january/my_image.jpg instead.

/images/january/my_image.jpg will always be interpreted relative to the root of the website. The web browser will request http://localhost/images/january/my_image.jpg for any page on http://localhost.

You can also use an absolute URL if you need to refer to an image on another web server, for example, http://otherhost/images/january/my_image.jpg.

Phil Ross
I use dirname(__FILE__) to define the path so that when I include the config file using include() the paths do not change in different directories. If I use define(IMAGE_DIR, '/images/') won't I run into trouble when including that config file in different directories?
sala_7
@sala_7 No you won't have any trouble with different directories. Regardless of the directory your page is in, a path starting with `/` will always refer to the same location on the web server.
Phil Ross
Thanks a million! I think I was getting confused with paths from an includes folder below the web root that use include() to import page parts from other directories
sala_7
A: 

It is better to use the constant "DIRECTORY_SEPARATOR" instead of '/' or '\'

Radek Suski