twigg
twigg

Reputation: 3993

PHP Include links

Hello I'm having my first serious go with PHP to create a sample script for my self. It has a basic structure, in my root folder I have:

All pages are made up by taking a header.php and footer.php from the includes folder and then each page has its own content in the middle. The header.php contains (as well as basic html and links to javascripts stylesheets ect) includes from core folder like so:

Now these all work great using the index.php which provides links to the 3 different sections of the site, sitea, siteb and sitec.

But when you navigate out of the document root to say /sites/sitea/index.php all those links are now broken.

What is the best way to go about building the links in the header.php section so they are relative site wide no matter which folder you are in?

Upvotes: 0

Views: 5198

Answers (3)

Adidi
Adidi

Reputation: 5253

The best way is to always use physical path from wherever you are - this way every page that include other page with includes won't get break:

PHP 5.2 and down:

require(dirname(__FILE__) . '/core/connect.php');

PHP 5.3 and above

require(__DIR__ . '/core/connect.php');

Upvotes: 1

AbsoluteƵERØ
AbsoluteƵERØ

Reputation: 7880

When you're including you want to use a real path, not a relative path...

require_once ($_SERVER['DOCUMENT_ROOT'].'/includes/header.php');
/* something happens here */
require_once ($_SERVER['DOCUMENT_ROOT'].'/includes/footer.php');

Upvotes: 1

Casey Dwayne
Casey Dwayne

Reputation: 2169

The idea behind this is that you do only have ONE file for each process.

So process all pages through index.php

index.php would contain, for example,

require('header.php');
include('content.php');
require('footer.php');

That way, it won't break the site if your content doesn't show.

Your index is always loaded from the same path, so header/footer wouldn't change. Just content.

Upvotes: 1

Related Questions