Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

include a file without breaking nested includes

Status
Not open for further replies.

theotrain

Programmer
Mar 5, 2003
150
MX
in my main directory on the server ive got a bunch of files that use includes to create a page header. the header itself includes information from several subdirectories, like "/images", "/css", "/includes", etc.

so now i want to have a page in a different directory use that same header. so i made a file with only the header data in it (in the main directory) so i could call it from somewhere else, like so:

Code:
include('../header_only.php');

but when i do that all the includes within "header_only.php" no longer work because they are seeing a different folder as the starting point.

so basically ive got a file that "includes" material from subdirectories, but the includes get lost if i include that main file from another location.

im sure this is a pretty common issue... what is the easiest way to get around this without duplicating code?
 
there are a number of ways to solve this problem.

The best is to include() files from a known base point. for example if you have a library file that you call at the start of every page (for example a db connect script) you could add this to it

Code:
$cDir = realpath(dirname(__FILE__));
define('BASE', $cDir);

then you can use the defined term BASE as the base for providing absolute URL's for each included file.
Code:
include BASE . DIRECTORY_SEPARATOR . 'mydir/myfile.php';

the second is to add to the included path in php.ini all paths on which you wish to place files that are to be included in other scripts.

if you are using this method you must not provide any path information in the call to include

[code]
include 'path/myfile.php'; //DO NOT USE
include 'myfile.php'; //OK

the third is to hard code absolute urls into each include/require
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top