ageadvert
ageadvert

Reputation: 35

How to make links from include() file relative to different PHP documents?

I am setting up my website to use the include() statement to standardize things like the header, footer, and navigation, e.g.

include('header.php);

However, when I use the same header file for pages in two different directories, the relative links contained within header.php break, e.g:

header.php
<a href="images/dog.jpg">

index.php
include('header.php);
becomes
<a href="images/dog.jpg">

This works because that is the correct path to dog.jpg from the index.php file.

animals/canine.php
include('header.php);
becomes
<a href="images/dog.jpg">

This DOES NOT work because animals/images/dog.jpg does not exist.

So, my question is, what can I change within the header.php file that will tailor the url to dog.jpg to work in both index.php and animals/canine.php when header.php is included?

Upvotes: 2

Views: 4310

Answers (2)

SamT
SamT

Reputation: 10630

Create a new variable called $root_path and put into it the path to the root of your web dir relative to the page you're on. Make sure it's declared before you include header.php

This is mysite.com/junk/index.php so your image assets are in ../images/

<?php
$root_path = '../'
include('header.php');

When outputting your asset urls, put $root_path in front of it.

Upvotes: 1

j08691
j08691

Reputation: 208032

Change the includes to use absolute paths:

<a href="/images/dog.jpg">

This way they'll be based off of the root of your site and always point to the proper folder.

Upvotes: 8

Related Questions