Using a header and footer for an entire site
If you have a site with many pages, or even one with few pages, and you would like not to update all your HTML files when the site design changes, you can use the include() function to implement a header and footer file that will be used on all your pages.
You can have anything in your header and footer. Basically the header file would typically have an opening <HTML> tag, the <HEAD> </HEAD> tags, and you can also include an opening <BODY> tag. Including a navigation menu, if it is going to be the same for the entire website, is also a good idea. The footer file could contain a copyright message, a closing <BODY> tag and/or HTML tag. These are just general suggestions about what to include in the header/footer.
Include() statement includes and evaluates the specified file. The path for the include command is set by the include_path setting in the php.ini file, which defaults to the current directory.
include("header.php"); - the current directory
The path to the file used in the include statement can be specified in relative or absolute terms.
include("../header.php"); - relative path meaning the directory above the current directory
or
include("http://www.somesite.com/somehere/header.php"); - absolute path to the file location
If you have included files that are outside of the web document path (not viewable by the browser) and you do not have access to the php.ini file, you can set the path of include directory with an .htaccess file.
Include the following:
php_value include_path ".:/include/dir"
If you do have access to php.ini file change the include_path to something similar:
include_path=/home/usr/phpinclude
Example header.php file:
PHP code:
Example footer.php file:
PHP code:
... perhaps other content in the footer file... </body> </html>
Using the header and footer file:
The $title variable will set the tile for your HTML page. By declaring the [$i]title
variable before you include the header file, the value variable is set within the header file.
PHP code:
<?php $title="Somesite.com: Unkown page"; include("header.php"); ?> ... other parts of the page ... <?php include("footer.php"); ?>
Note: Make sure your include files do not begin or end with a blank line. If you are planning to use cookies, sessions or other headers you will get an error similar to this:
Warning: Cannot send session cache limiter - headers already sent
Apache considers the include files a source of HTML, so that blank line will be the first line of the document. When you try to set a cookie or session header, Apache can not set it because it has already started sending the document with the blank line.