Reputation: 31
I am trying to include my header.php & footer.php file that I have created into every page. And so far its been working!
As soon as I created a new directory e.g /new-site-area - when I then created a new php page and tried to include the header.php this then didn't seam to work?
This is the php include that I am using, and it is working...
<?php include ("includes/header.php");?>
It just seems to stop working as soon as I try to include it into a page that is in a /directory.
Example:
www.mysite.com - header include works
www.mysite.com/new-directory/new-area - header include doesn't work
I can't understand why it would work on my websites root, however not as soon as the page is in a different /area of my site.
If this is an unfixable problem could somebody please advise a better way of including php files into a site page!
Thanks!
Upvotes: 0
Views: 77
Reputation: 1323
You have to browse into your directory with the return argument "../"
for example, your page
www.mysite.com/new-directory/
should use
<?php include ("../includes/header.php");?>
for a 2 level folder like
www.mysite.com/new-directory/new-directory2
It should be
<?php include ("../../includes/header.php");?>
Upvotes: 2
Reputation: 1375
Try include "../includes/header.php"
- the best would be to write some function that would include it right, for example:
function load($file) {
return $_SERVER['DOCUMENT_ROOT']."/includes/$file";
}
then just use include(load("header.php"));
Or if you want your load()
function to support multiple paths, try something like this:
function load($file) {
$paths = array(
"includes",
"some_other_dir/includes"
);
foreach($paths as $path) {
if(file_exists($_SERVER['DOCUMENT_ROOT']."/$path/$file")) {
return $_SERVER['DOCUMENT_ROOT']."/$path/$file";
}
}
trigger_error("File $file not found in any of paths", E_USER_ERROR);
}
Then if the file is in any of paths specified, it will be included via include(load("file.php"));
, if the file does not exist it will throw an error.
Upvotes: 1
Reputation: 3426
Use a framework if you don't want to implement a way of resolving the path of your includes. There is a lot of small frameworks that handle this and many other problems.
Upvotes: 0