Wes
Wes

Reputation: 1

Parent directories and PHP

I really hope there's a simple solution to this.

<?php include("header.php"); ?>

Let's say I have a php header in my root folder simply titled header.php. In that header there is a link back to the home page, main.php, and main.php is also located on the root. No problem so far. Here's what header.php looks like. Simple stuff, right?

<link href="style.css" rel="stylesheet" type="text/css" />

<div id="headerwrap">

        <div id="linkbox">
            <a href="main.php"><img src="images/mainlogo.png" /></a>
        </div><!-- End linkbox -->

</div>

However, let's say I have other pages in subdirectories. Subpage.php is located in a child directory of the root, and so it has to look back to the root to get the included header.php.

<?php include("../header.php"); ?>

That wouldn't be a big deal, except that header.php links back to main.php and also style sheets, none of which are in *subpage.php's directory, thus causing an error when someone on Subpage tries to get back to Main via the link in the header.

I'm just hoping there's a simple way to make this work, and that I don't have to copy and redirect all includes into every subdirectory. Also, there are too many pages to really reasonably include them all on the root. Sorry if this answer is posted elsewhere; I've looked and just have no real idea what I'm looking for. Thanks for your help. Hope all that makes sense.

Upvotes: 0

Views: 1399

Answers (5)

Zak
Zak

Reputation: 25205

As opposed to a php prob this seems to be an html prob..

Your links should be relative links with a preceding / i.e.

<a href="/main.php"> Text </a>

instead of

<a href="main.php"> Text </a>

Upvotes: 1

tatorface
tatorface

Reputation: 72

You could just hard code main.php's path within header.php:

<a href="http://website.com/main.php"><img src="http://website.com/images/mainlogo.png" /></a>

Upvotes: 1

kennypu
kennypu

Reputation: 6051

the best thing to do is to get in the habit of using

$_SERVER['DOCUMENT_ROOT']

that way you have no confusion as to what directory you're in, etc.

so including your header for example would be as simple as :

include $_SERVER['DOCUMENT_ROOT'] . "/header.php";

Upvotes: 0

Eduardo Reveles
Eduardo Reveles

Reputation: 2175

You can use the base html tag:

<base href="http://yoursite.com/" />

This way you can use that url as the base for all your links/stylesheets/images and you don't need to worry if they're in a subdirectory.

Upvotes: 0

mschmoock
mschmoock

Reputation: 20854

how about using absolute links. header.php should also reference main.php absolutely, then there should be no troubles:

<?php include($_SERVER['DOCUMENT_ROOT'].'/header.php"); ?>

Upvotes: 0

Related Questions