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 learning php, been trying to make a cms, but when I use an include for the header this results in the page appearing as if it were written in pre tags. There's no errors when I debug or anything. And I'm completely stumped. When I put the header back in without the include it renders just fine.
<?php include("..\includes\layouts\header.php"); ?>
That's the include I'm using.
I've tried using the full path name, tried it in different browsers and using :
include($_SERVER["DOCUMENT_ROOT"]
Check that you are closing your php tags, ending your strings with semi colons etc.. My guess is that your html is being sucked into the php code which freaks out and just dumps it.
Maybe try one of the validators such as http://phpcodechecker.com (I have not used this one so I cannot comment on it's effectiveness)
Edit: I am rereading your post and I think I understand what you are trying to say - your header contains the path to your css and when you put it in a separate php file the css doesn't work? So the first thing to do is determine if the issue with the php path or the css path inside the header.php file. Look at your source code to see if the header code is being included - if it is then play around with the css path - though including the header in a php file will not cause that css path to change.
I am guessing that your header is not included at all from your mention of paths. include() works from the loading file's location. The path it wants is a server path and not a url. The one that you have above: ../includes... means that you have an include folder at the same level as the loading file such as (assume index.php is the main file):
/includes/layouts/header.php
/somedirectory/index.php
The ../ means - drop down one directory then go up from there.
If your path is more like:
/includes/layouts/header.php
/index.php
Then the include would be:
include('./includes/layouts/header.php');
Let me know if that works - if it doesn't try to explain your directory structure.
So I'm trying to make a theme from my Html file. And using require('file.php') where file.php is a series of different components of my theme. Now when I access the file directly, I still see the html. How do I make it display a blank page when user accesses the file.php directly?
Explanation
So let's say I make index.php and I want to include the header file(header.php)
When I require('header.php'), everything works perfect. Now when I try to access the header.php, I can see the html content of it. How to I make this appear blank instead of seeing the header.php piece?
Thanks
In that case, If you want to execute header.php inside the index.php or etc. You need to add or define a flag in parent files (wherever you want header.php to be executed or simply adding in to the common file which is called in all parent files), In header.php file you need check the defined flag is set or has some value. If it is not set, then stop execution by using die(); function.
In index.php,
<?php $HeaderAllow ='1'; ?>
In header file,
<?php
if($HeaderAllow=='' or !isset($HeaderAllow)){
die();
}
?>
you can use $_SERVER['SCRIPT_FILENAME'] here to check and then make page blank in header.php.
<?php
if($_SERVER['SCRIPT_FILENAME'] == 'header.php') {
exit();
}
Putting the include files in a seperate folder and protectinng with .htaccess is good idea.
Same issue here.
deny direct access to a folder and file by htaccess
The easiest way is to put your includes in a directory and deny access to that directory in your .htaccess file
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 am wondering how I can break up my index.php homepage to multiple php pages (i.e. header.php, footer.php) and build a working index.php page using those separate php pages. I know WordPress uses this with different functions like:
GetHeader();
GetFoodter();
But when I tried to use those functions, it errors. I am guessing they are not native functions to PHP.
What would I need to do to get this functionality?
include 'header.php';
include 'footer.php';
Go with an MVC framework like Zend's. That way you'll keep more maintainable code.
You could do the following:
<?php
include('header.php');
// Template Processing Code
include('footer.php');
?>
The include() statement includes and evaluates the specified file.
so if you create index.php as:
<?php
include("1.php"); include("2.php"); include("3.php");
?>
processing it will combine three php files (result of parsing them by php) into output of your index.php ... check more at http://pl.php.net/manual/pl/function.include.php
Also, if i recall correctly, you can also use
<?php
require('filename');
?>
the difference being, if php can't find the file you want to include, it will stop right there instead of keep excecuting the script...
If your server is configured accordingly, you can use PHP's built in auto append/prepend settings and set it in a .htaccess file:
php_value auto_prepend_file "header.php"
php_value auto_append_file "footer.php"
Info:
www.php.net/manual/en/configuration.changes.php#configuration.changes.apache
www.php.net/ini.core#ini.auto-prepend-file
www.php.net/ini.core#ini.auto-append-file
I realize this is an old question, which already has a perfectly valid accepted answer, but I wanted to add a little more information.
While include 'file.php'; is fine on it's own, there are benefits to wrapping these sorts of things up in functions, such as providing scope.
I'm somewhat new to PHP, so last night I was playing with breaking things into files such as 'header.php', 'footer.php', 'menu.php' for the first time.
One issue I had was that I wanted to have the menu item for a page/section highlighted differently when you were on that page or in that section. I.e. the same way 'Questions' is highlighted in orange on this page on StackOverflow. I could define a variable on each page which would be used in the include, but this made the variable sort of global. If you wrap the include in a function, you can define variables with local scope to handle it.
You could also look into a template engine like Smarty. That way you define the the header and footer and all other common elements in a single file, then fill in the rest through smaller templates or direct output.
Use include statements to just include those files to your Page
I think it's
include '[filename]'