Question

In my public_html folder I have the following directories:

- includes (in here I have header.php which is included in index.php)
- images
- styles
- scripts

index.php includes header.php, which is where I reference my stylesheets, scripts, images etc.

All is fine until I try loading a page directly from the includes directory which also includes header.php, for example:

WORKING: www.mysite.com/index.php

NOT WORKING: www.mysite.com/includes/example_page.php (where example page also includes header.php)

In example.php none of the stylesheets, images or scripts are loading. This is because it is looking for them in public_html/includes. Obviously changing the file paths to ../styles/stylesheet.css works. But this isn't an ideal solution, especially if I have to change the file path for every image in header.php.

How can I detect if a page is in the includes sub-directory set the file paths to point to public_html?

chdir(); doesn't seem to work.

Was it helpful?

Solution

Use absolute paths in your HTML/CSS, e.g.

<link rel="stylesheet" href="/css/styles.css" />
                             ^--- start at top of site document root

<img src="/images/kittens.jpg" />
          ^--- start at top of site document root

Then it won't matte WHERE you put your scripts, the hrefs/src's will always start at the TOP of your site's URL-space and work their way down.

What you lose from this is the ability to host this particular site in a subdirectory, e.g. if you decide to move it to

http://example.com/oldsite/index.php

all of your paths would in the href/src would have to re-written to say /oldsite/images/kittens.jpg or /oldsite/css/styles.css.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top