I have a problem with including header.php and footer.php on my index.php
The structure of the website is like this.
I have an index.php page and I have also 4 folders which are (about us), (support), (assets), (includes) that they have pages inside those folders. In the (includes) folder I have header.php and footer.php. In my (assets) folder I have 2 folders which are (css), (js). Inside my (css) folder I have my style.css file and in the (js) folder I have my custom.js file.
In my (includes) folder, the header.php file is including the style.css like this. . Moreover, in my (includes) folder the footer.php file is including the custom.js like this.
Furthermore, in my (about us) folder I have about-us.php page. When I use <?php include "../includes/header.php"; ?> and <?php include "../includes/footer.php"; ?>, it all works normal.
My problem is this. When I try to include header.php or footer.php in my index.php page they do not work. I have tried to include them like <?php include “/includes/header.php"; ?> and <?php include "includes/footer.php"; ?> but they do not work. I have tried different methods but nothing is working. The problem is that I can include header.php and footer.php in my sub pages which are inside a folder but not in the index.php which is outside a folder. In addition, If i have to make any change to the header or footer I will have to change it twice, one for the index.php which will be hardcoded and one in the header.php or footer.php which are included in the sub pages.
How can I make it so I can include header.php and footer.php from the (includes) in my index.php page and also working on about-us.php page which is inside the (about us) folder ?
Thanks.
Referencing files is difficult [non-intuative (pick a word)] when you are bouncing around different levels of a folder structure. You could write a book on relative and absolute file paths.
If might be better, before your site gets too big to create yourself a config.php file, define a proper base URL for your site, and then include that in each of your pages, along with that, that you are trying to reference.
For example. In the root directory of your site, create a file called config.php and use the following:
<?php
define("ROOT_PATH", $_SERVER["DOCUMENT_ROOT"]);
Then in ALL of your other files, you can reference the config.php file first, which will define the ROOT_PATH for that document, and then call your other files.
So in your header.php file
<?php
include "./config.php";
include(ROOT_PATH . "/assets/css/style.css");
Then when you call header.php from index.php, header.php will have the absolute route to the CSS file to reference.
I hope I have explained that well enough.
EDIT / ADDITION:
config.php files are a handy addition to any PHP project for many other things as well as defining URLS. You can keep your DB connections in there, arrays of static things you use often etc. They become the "go to" place for consistently used things.
This will work.
include "./includes/header.php";
Otherwise, you can include the full file path location of the header.php and footer.php in the index.php
I have three pages on my localhost 1 is my index page,2 is my universal header page which is under includes folder of and 3 is my html file which is under html folder.The header file is included in both the index file and html file like that...
for index.php-include("includes/header.php");
for html.php-include("../includes/header.php");
and my header has the link of index.php page that is (./index.php)
Now my questions is that when i open my index page and click on link of index page from my header it takes me to same index.php page but when in open html.php page and then click index.php page link from header it does not go to index.php page but it goes to this page-
(localhost/educational%20website/html/index.php) how to solve that.
And i also want to know that write now i am on localhost but when i make my site live is there any need to change the paths because i am making around 150 pages with your technique plaese so please answer me that kind of technique that is used for both localhost and on live
Your are including paths relatively, use a (absolute) base path in your index.php to fix this:
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/header.php');
One way is to define a variable or a constant for the site's url in the header.php file. Then in all your other pages, you could just use this variable/constant when you need to mention the other urls.
Eg(put this as first line in your header.php file):
define('SITE_URL', 'http://localhost/educationalwebsite');
Here, we have defined a constant named SITE_URL. Then in other pages, you are already including this header file. Isn't it? So, this constant will be available in your index.php, html.php and other pages.
And suppose for a link in your html.php file(to point to the index.php), you could use it like this:
Home
If you want to include link to the html.php file residing inside html folder, it would be like:
HTML
By using this way, if you are uploading the whole site to a live server, you only need to change one line, ie. the first line in header.php, where we have defined the SITE_URL constant. Just change it's value to the new URL of the home directory of your website.
Hope this helps
UPDATE 1: to have a clear view of what is happening, you can download a snippet of the script from here.
I am working in a new website that has the same header, footer in all PHP pages.
In the header I am referencing to other common files in website that like .css, .js, functions, classes, db connection, and etc.
for instance, the default.css is in /common/stylesheets/
and my header.php and footer.php are in /common/html/ folder
so my header.php file is something like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Header</title>
<link rel="stylesheet" href="common/stylesheets/default.css">
</head>
<body>
In my website index.php I included the header <?php include('common/html/header.php'); ?> and this is working fine... BUT the problems appear when I include the header in other php pages within other directories or sub directories e.g. /pages/admin/dashboard.php, everything messed up and that page no more linked to the default.css file.
So, what I am looking for is a method or logic where I reference to these common files and folders in every PHP page no matter its location; e.g. site root, a directory in the site root, or a sub-directory... etc...
here is an image of my website root
Your help is highly appreciated...
P.S. I've tried to use some superglobals variables such as $_SERVER[''] in config.inc.php file to define the paths, then I included that file in the header.php. BUT I couldn't figure out which one will dynamically keep referencing to those common folders and files no mater where the PHP page is.
UPDATE 1: to have a clear view of what is happening, you can download a snippet of the script from here.
It is usually a good idea to use fully qualified or absolute URLs to reference your assets:
<link rel="stylesheet" href="http://www.sitenamecom/some/path/to/common/stylesheets/default.css">
Since there are many places where you need the proper URL base to reach the different files, you could define a constant having the web root:
define('WEB_ROOT', 'http://www.sitename.com');
Then you could define other constants to have access to the different parts of the system:
define('WEB_ASSETS', WEB_ROOT . '/common');
So for the style sheet link in your header.php it would be:
<link rel="stylesheet" href="<?php echo WEB_ASSETS; ?>/stylesheets/default.css">
To include files the principle is the same only that in this case you don't work with URLs but with file system's paths. There's not really a dynamic way of solving this, it all goes down to absolute paths.
The problem here is that the tree structure in your local development environment might (and surely won't) match that of your server. So in the configuration file, which is located in your application's root you could define:
define('APP_ROOT', dirname(__FILE__));
Then lets use the admin/index.php file as example:
include '../../../config.inc.php';
include APP_ROOT . '/sitename/common/html/header.php';
The tricky part here is including the configuration. Since, until you do that the APP_ROOT won't be available, relative paths are needed to reach it, and it isn't possible to escape this one; unless you can fully trust the preferred absolute form:
include '/some/path/to/config.inc.php';
Having that leading slash, as I said before, will be a problem if the application is tested in different environments because it is rarely the case that some/path/to is always the same.
This is the usual issue with structures that aren't using index.php for centralization. Maybe you can try adding another include that defines your directories as pseudo-constant and prepending them to your asset urls.
Or you can parse the request url on how deep it is and automatically prepend the needed ../ levels to your assets urls. I've done this for one of my past projects.
I got to warn you though, it's better to solve the root of the issue (lack of centralization) than adding workarounds. It will surely come back to haunt you sooner than you think.
$_SERVER['DOCUMENT_ROOT'] is likely what you are looking for.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/sitename/common/html/header.php");
This should work from any directory. If you want it to be a little more dynamic than typing out "sitename", you can do this:
<?php
$sitename = explode("/", $_SERVER['REQUEST_URI']);
require_once($_SERVER['DOCUMENT_ROOT'] . "/" . $sitename[1] . "/common/html/header.php");
You need to Change your <link rel="stylesheet" href="common/stylesheets/default.css"> to <link rel="stylesheet" href="../../common/stylesheets/default.css">
here is a simple modification in php.ini to include footer.php and header.php for each script
auto_append_file=ABSOLUTE_PATH/footer.php
auto_prepend_file=ABSOLUTE_PATH/header.php
restart your Apache if you are running under easyPhp, xampp,....
Warning : This configuration will be applied in all projects that are executed with the modified PHP
Try <link rel="stylesheet" href="/common/stylesheets/default.css">
Note the leading slash... This directs server to the document root.
I tried it and it works.
My tree:
/var/www/html/
subdir/
body.php
layout/
header.php
footer.php
css/
style.css
header.php
<html>
<head>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<p>Header.</p>
<hr>
body.php
<?php
include($_SERVER['DOCUMENT_ROOT'].'/layout/header.php');
echo "Body.<br>";
include($_SERVER['DOCUMENT_ROOT'].'/layout/footer.php');
?>
footer.php
</body>
</html>
style.css
body {
color: red;
}
Viewing http://localhost/subdir/body.php in the browser, I get the expected result: "Header" and "Body" are colored red.
I would store the document root of your website in some define:
define('DOCROOT', $_SERVER['DOCUMENT_ROOT']);
Do this in a PHP file that you include everywhere, preferably in some bootstrap PHP file.
Then you need to prepend your paths with this in your include lines:
<?php include(DOCROOT . "/common/html/header.php"); ?>
Have you also looked at include_once?
Have you tried PHP's set_include_path ?
You can add numerous paths in one set_include_path separating them with a ' :'.
set_include_path('/home/mysite/includes1:/home/mysite/includes2').
PHP.net -> set_include_path
Even without moving to a full front controller (and MVC) setup (which would be good), you are going to save yourself a lot of headaches if you introduce a simple bootstrap-like file.
It's not going to be perfect with your current setup, as your files are including different parts of your system (ie header.php) in various places and sub folders.
Having header load the first output things - i.e. doctype, head and head links etc - is fine in your basic structure, but you have now run into constraints which you cannot work around without making your header.php messy, or including numerous other files before header.php.
In a more solid framework design, the html and doctype outputs are after a lot of other things have been initiated and loaded, to allow control over said html and doctype.
But to help in your case, just load the bootstrap before anything else is loaded/included.
Bootstrap
The bootstrap will load shared resources, and common used data and paths (etc) throughout your application.
You can then add anything else in the bootstrap in the future, if you find a scenario.
A simple example of something in your bootstrap:
bootstrap.php (MUST reside in your root web folder for following constant to work)
// Define root folder
define ('FOLDER_ROOT', __DIR__);
Then throughout your app you can reference that constant (FOLDER_ROOT) to determine the root folder, and work through subfolders as required.
So, using your current setup:
index.php (I presume is in root folder)
include('bootstrap.php');
include(FOLDER_ROOT.'/common/html/header.php');
// Everything else
So then in your bootstrap you can set other things, such as define the default doctype or character encoding, setup error management.
Although you would usually set things like doctype after bootstrap, in a class, the router, some controller, or even a template.
But as you are using common file includes rather than using a more conventional framework design pattern, this way will at least save you some headaches now, and possibly further down the line.
So again in the bootstrap.php:
// Define root folder
define ('FOLDER_ROOT', __DIR__);
// Define CSS folder using root folder constant above
define ('FOLDER_CSS', FOLDER_ROOT.'/common/stylesheets/');
Then in header.php:
echo '<link rel="stylesheet" type="text/css" href="'.FOLDER_CSS.'default.css">';
Sub Folders (ie /admin)
Now in sub folders, such as /pages/admin/dashboard.php etc, you don't have access to these constants, because you are loading your header files and other template like things all separately "across your application".
So it becomes a battle to set your root folder, plus you are now managing it all twice!
You could try loading the root bootstrap file within your admin folder.
So in dashboard.php, something like:
include('/bootstrap.php');
// OR (more likely)
include('../../bootstrap.php');
But this is becoming messy, calling bootstrap in different places, having to call it differently too.
It's not ideal, but it is do-able, in that if you get the bootstrap loaded within your admin area, then you have the root path setup in admin area and so managing other files from your admin files should be easier.
You could try using a new admin specific bootstrap file, eg in /pages/admin/, have adminBootstrap.php.
But then you're setting two different constants for root, and likely more constants to get to your common and css files and folders. It's easy setting your web root path in a file that is in the web root path, and can be tricky (sometimes) setting web root path from another folder.
Stylesheets
You mentioned that using /common/stylesheets/defaults.css (with a preceding slash) doesn't work and causes the source code to show localhost/common/stylesheets/defaults.css.
This would possibly indicate you need to configure your DocumentRoot.
On Linux it's in /etc/apache2/sites-available/, then either the default file, or if you configured your own virtual sites then go into each one.
What is your DocumentRoot set as?
Although if you get the bootstrap working within the admin area this problem might go away, using the constant FOLDER_CSS.
Folder Structure
I also think you should tidy up your folders, as you seem to have separated things into illogical folder names (perhaps logical to you, but will it be when you learn more and come back to it in a year, or another dev tries to use it?).
E.G. I would not know what on earth the folder html is going to contain, as HTML is a protocol, and ultimately your application will serve HTML.
Have a little read into MVC. Don't go into depth as it's a lot of reading/learning, but if you grasp the basics, you can then tidy up your own structure to create your own logical separation of presentation from business a little more logically than it is now.
Front Controller
If instead of using include files, you had a framework, which loads bootstrap and application wide configs, error management, other stuff, then when you come to load your HTML (your header, footer etc), they will have all this application (root folder constants etc) pre-loaded regardless of which sub folder you are trying to load web pages from.
However as you are doing it, you are instead including these things manually whenever you need them in different files, in sub folders.
While you are introducing a small presence of DRY (Don't Repeat Yourself) by having the doctype, head, etc in include files and re-using them, you are still having to repeat yourself with those include files as you re-use them wherever you need them.
Also, what if you wanted to re-style admin differently to the main site? You'd have to include a different header file or a different stylesheet, or just put all code in the same stylesheet.
I'm waffling, but hopefully I'm being clear, and you can see why using header includes is only a small step in the right direction and for small sites. I'm sure you progressed naturally to using those include files from typing out the head/doctype etc in every file.
However now you are trying to break out into other directions, as with your admin area, you can see the constraints and including those same files is becoming harder to manage as your entire application grows.
So if you had a front controller type setup, within your dashboard.php you would have been able to simply used the constants set in the root bootstrap file, and any other sub folder which would be accessed after the core application is loaded.
EG (if using front controller like pattern)
dashboard.php:
include(FOLDER_ROOT.'/common/html/header.php');
I know I've bashed on about front controller already, but a few years back I was at the stage you are now, and moved from having all my files including the header.php, then the page content, then including footer.php, etc, and I instead started using a front controller.
It's really sooo much better!
It is a fair learning curve (with learning curves in all sorts of directions and methods, requirements, etc) and as such will leave it up to you if you want to go further into that.
I now have my own basic MVC front controller system, which I just simply plonk a new file for a new website page into the view/pages folder, and the page can be used immediately in the browser (the system does everything else).
I'm working ona site and It's becoming more complex with folder structure. I'm sure this is a simple problem for most but I keep getting mixed results.
my folder structure is something like:
Root:
assets
css
js
images
core
init.php
categories
sub category
file.php
includes
header.php
footer.php
and so on.
the init file will be included at the top of every document, excluding the header and footer.
the header and footer are included in every page.
I'd like to achieve something where instead of writing include '../../includes/footer.php' or include '../includes/footer.php' I can just write include '$root. /includes/footer.php' and not need to worry about the links.
The same applies for my nav bar (which is located in the header) if i want to go to index and i'm in a sub folder then it tries to take me to site/subFolder/index.php which doesn't exist. I'd like to use the same idea her and have the nav links as root. file location
Could someone please help? It's killing me and I'm certain it's so simple I'm looking past the obvious.
I've outputted DIR and SERVER_ROOT
I can hash something together using
$bla = $_SERVER['DOCUMENT_ROOT'];//= c:/www
$bla.= "/nameOfMyRootFolder";
but wondering what the best way is as i keep seeing references to DIR
thanks!
$_SERVER['DOCUMENT_ROOT'] is defined in the webserver config and generally doesn't change.
__DIR__ is the directory that the file it is used in resides.
eg: in docroot/includes/header.php __DIR__ == 'docroot/includes' and $_SERVER['DOCUMENT_ROOT'] == 'docroot'
Documentation
I've managed to teach myself PHP/PDO/SQL, and yet, I cannot for the life of me figure out how relative paths work in PHP & HTML. I've got a multipage website with a few directories and branches, and I want to be able to create a simple template I can use to make new pages, without having to change the links to my stylesheets and PHP includes every time, depending on directory.
Here's my layout as follows:
MySite (http://localhost/MySite/)
RESOURCES //Not a folder, just here for readability
> serverside > initialize.php
> templates > header.php
footer.php
navuser.php
navmenu.php
> styles > styles.css
> images > variousImages.png
PAGES //Not a folder, just here for readability
> index.php
login.php
register.php
gettingstarted.php
> you > settings > settings.php
> youraccount.php
> yourfavourites.php
Here are the rules of the game: Each page first includes the serverside/initialize.php file (PHP include). Then, each page includes styles/styles.css through a standard HTML href attribute. Each page then includes via PHP both templates/header.php and templates/footer.php, with the former ALSO containing templates/navuser.php, and templates/navmenu.php.
The problem is, if one of the pages is in on a different level (say you/settings/settings.php, for example), then all those includes and hrefs have to change, which seemingly affects the includes inside the includes. It's impossible!
All I want is to be able to specify file names without using true absolute paths so I can have a single template file to duplicate throughout my website if needed - I've looked into __DIR__, __FILE__, $_SERVER['DOCUMENT_ROOT'], casting a variable $dir to act as a document root, but to no success. I don't understand half of what's happening either.
Can anyone shed some light on my situation? I'm essentially looking for a complete explanation of how relative roots/links/files are meant to work in PHP. How do I deal with even more complex directory structures? Again, what should I do? Thanks.
You would usually set a constant containing an absolute path and absolute URL in your index.php file, and then reference them from there on in includes etc.
An example index.php:
<?php
define('ROOT_DIR', __DIR__);
You can then use that constant thereafter:
require ROOT_DIR . '/includes/database.php';
require ROOT_DIR . '/application/controllers/MyController.php';
require ROOT_DIR . '/application/models/MyModel.php';
And so on. Hope this helps.