One of the most powerful features of PHP is its ability to include external files within a PHP document. This functionality enables developers to create modular, maintainable websites by breaking down the code into reusable components. Today, we'll explore how to implement headers and footers across multiple pages using PHP includes.
"Don't repeat yourself" (DRY) is a fundamental principle of software development. PHP includes are one of the simplest and most effective ways to implement this principle in web development.
The Problem of Repetition in Web Development
Without PHP includes, the same header and footer code must be repeated across every page, leading to maintenance nightmares when updates are needed.
The Solution: PHP Includes
With PHP includes, header and footer code is maintained in separate files and included where needed, making updates simple and consistent.
How PHP Include Statements Work
Understanding File Inclusion
PHP provides several statements for including external files:
Statement
Description
Error Handling
include
Includes and evaluates the specified file
Produces a warning if file not found, but script continues
require
Same as include, but more strict
Produces a fatal error if file not found, script stops
include_once
Includes the file if it hasn't been included before
Warning if file not found, script continues
require_once
Requires the file if it hasn't been included before
Fatal error if file not found, script stops
Analogy: Library Books
Think of PHP includes like borrowing books from a library:
include is like asking to borrow a book - if the book isn't available, you're disappointed but continue with your day.
require is like needing a textbook for an exam - if it's not available, you can't proceed with the exam at all.
include_once and require_once are like checking if you've already borrowed a book before requesting it again - they prevent duplication.
How PHP Processes Includes
When PHP encounters an include or require statement, it stops processing the current file, switches to the specified file, executes it, and then returns to continue processing the original file. The included file's code is executed as if it were part of the main file.
Creating Reusable Header and Footer Files
Step 1: Directory Structure
First, let's organize our project with a logical file structure:
This structure separates our reusable components (includes), stylesheets (CSS), scripts (JS), and content pages. This organization makes it easier to maintain and update our website.
Step 2: Creating the Header File
Let's create a basic header file that contains all the common elements at the top of each page:
Closes the main content container and main element that were opened in the header
Contains a structured footer with multiple columns
Uses PHP's date() function to dynamically display the current year in the copyright notice
Includes conditional page-specific scripts that can be defined on individual pages
Closes the HTML document that was opened in the header
Step 5: Using the Include Files in a Page
Now, let's create a content page that uses our header and footer:
index.php
<?php
// Define page-specific variables
$pageTitle = "Home";
$currentPage = "home";
// Include the header
include 'includes/header.php';
?>
<!-- Page-specific content starts here -->
<section class="hero">
<h2>Welcome to Our Website</h2>
<p>This is the homepage of our website built with PHP includes.</p>
<a href="about.php" class="btn">Learn More</a>
</section>
<section class="features">
<div class="feature">
<h3>Feature 1</h3>
<p>Description of the first feature.</p>
</div>
<div class="feature">
<h3>Feature 2</h3>
<p>Description of the second feature.</p>
</div>
<div class="feature">
<h3>Feature 3</h3>
<p>Description of the third feature.</p>
</div>
</section>
<!-- Page-specific content ends here -->
<?php
// Optional: Add page-specific scripts
$pageSpecificScripts = '<script src="/js/home.js"></script>';
// Include the footer
include 'includes/footer.php';
?>
Here's what's happening in our index.php file:
We define page-specific variables ($pageTitle and $currentPage) that will be used in our includes
We include the header file, which brings in all the HTML structure up to the main content area
We add our page-specific content
We optionally define page-specific scripts
We include the footer, which completes the HTML structure
Creating Additional Pages
For additional pages, we follow the same pattern, just changing the page-specific variables and content:
about.php
<?php
// Define page-specific variables
$pageTitle = "About Us";
$currentPage = "about";
// Include the header
include 'includes/header.php';
?>
<!-- Page-specific content for About page -->
<section class="about-content">
<h2>Our Story</h2>
<p>Content about your company history...</p>
<h2>Our Team</h2>
<div class="team-members">
<!-- Team member profiles here -->
</div>
</section>
<?php
// Include the footer
include 'includes/footer.php';
?>
Advanced PHP Include Techniques
Using Variables and Constants in Includes
PHP includes can access variables defined in the parent file before the include statement, and any variables defined in the included file are available to the parent file after the include statement.
<?php
// index.php
include 'includes/config.php';
// Now we can use the config variables
echo "<title>$siteName - Home</title>";
// Include header after configuration is loaded
include 'includes/header.php';
?>
Using Include_Once for Configuration Files
When working with configuration files or function definitions, it's often safer to use include_once or require_once to prevent redefinition errors.
Example: Using include_once for Database Connection
<?php
// Using the connection function in multiple files
include_once 'includes/db_connect.php';
// Now we can use the connection function
$conn = connectToDatabase();
// Do database operations
?>
Using include_once ensures that even if our database connection file is included multiple times (perhaps by different include files), the function won't be redeclared, which would cause an error.
Using Path Constants for Includes
For larger projects, it's helpful to define path constants to make your includes more reliable, especially when including files from different directory levels.
Example: Defining Path Constants
<?php
// config.php (at root of site)
// Define site root path
define('SITE_ROOT', __DIR__);
// Define paths to common directories
define('INCLUDES_PATH', SITE_ROOT . '/includes/');
define('TEMPLATES_PATH', SITE_ROOT . '/templates/');
define('UPLOADS_PATH', SITE_ROOT . '/uploads/');
// Now we can use these constants in any file
require_once(INCLUDES_PATH . 'header.php');
?>
Using constants for paths has several advantages:
Makes your code more maintainable - if you reorganize your folders, you only need to update the constants
Prevents path-related errors when including files from different directory depths
Makes your code more readable by clearly indicating where files are located
Real-World Applications in WordPress
Understanding WordPress Template Hierarchy
WordPress uses a sophisticated template system that relies heavily on PHP includes. Understanding this system will help you develop WordPress themes effectively.
In WordPress:
Template files like single.php, page.php, etc. determine the main content structure
These template files include common elements using WordPress functions like get_header() and get_footer()
Behind the scenes, these functions use PHP's require() to include header.php and footer.php
WordPress Theme Include Functions
WordPress provides several functions that are wrappers around PHP's include statements:
WordPress Function
PHP Equivalent
Common Usage
get_header()
require(TEMPLATEPATH . '/header.php')
Include the theme's header.php file
get_footer()
require(TEMPLATEPATH . '/footer.php')
Include the theme's footer.php file
get_sidebar()
require(TEMPLATEPATH . '/sidebar.php')
Include the theme's sidebar.php file
get_template_part('part-name')
require(locate_template('part-name.php'))
Include reusable template parts
Example: WordPress Theme Structure
<?php
// page.php in a WordPress theme
get_header(); // Includes header.php
?>
<div class="content-area">
<main class="site-main">
<?php
while (have_posts()) :
the_post();
get_template_part('template-parts/content', 'page');
// If comments are open or we have at least one comment
if (comments_open() || get_comments_number()) :
comments_template();
endif;
endwhile;
?>
</main>
<?php get_sidebar(); // Includes sidebar.php ?>
</div>
<?php get_footer(); // Includes footer.php ?>
In a WordPress theme:
get_header() includes the header.php file
get_sidebar() includes the sidebar.php file
get_footer() includes the footer.php file
get_template_part('template-parts/content', 'page') looks for template-parts/content-page.php, and if not found, falls back to template-parts/content.php
Creating Template Parts in WordPress
WordPress's get_template_part() function is a powerful way to create modular themes:
<?php
// single.php (for blog posts)
get_header();
?>
<main id="main" class="site-main">
<?php
while (have_posts()) :
the_post();
get_template_part('template-parts/content', get_post_type());
// If comments are open or we have at least one comment
if (comments_open() || get_comments_number()) :
comments_template();
endif;
// Post navigation
the_post_navigation();
endwhile;
?>
</main>
<?php
get_sidebar();
get_footer();
?>
This approach offers several advantages:
Keeps your theme DRY (Don't Repeat Yourself)
Makes maintenance easier - update a template part once, and it updates across the site
Allows for content-specific variations (like content-page.php, content-post.php)
Improves code organization and readability
Best Practices for PHP Includes
Security Considerations
Never Include User-Supplied Filenames
One of the most dangerous security vulnerabilities is allowing user input to determine which files to include.
Vulnerable Code (NEVER DO THIS):
<?php
// DANGEROUS - Never do this!
$page = $_GET['page'];
include($page . '.php'); // An attacker could use this for remote file inclusion!
?>
Using relative paths can lead to security vulnerabilities if PHP's include_path is configured insecurely. When possible, use absolute paths defined in constants.
<?php
// Define base path (typically in a config file)
define('BASE_PATH', __DIR__);
// Use the constant for includes
include(BASE_PATH . '/includes/header.php');
?>
Performance Considerations
Use include_once and require_once Judiciously
include_once and require_once are slightly slower than their regular counterparts because PHP must check if the file has already been included. Use them only when necessary to prevent redefinition errors.
Consider Using Output Buffering
For large, complex pages with multiple includes, output buffering can improve performance by sending content to the browser all at once rather than in pieces.
<?php
// Start output buffering
ob_start();
// Include all your files
include 'includes/header.php';
include 'content/home-content.php';
include 'includes/sidebar.php';
include 'includes/footer.php';
// Get the content and send it all at once
$content = ob_get_clean();
echo $content;
?>
Maintainability Best Practices
Create a Consistent File Structure
Organize your includes in a logical directory structure that makes it easy to find files:
includes/ - Header, footer, and other structural elements
includes/components/ - Reusable UI components
includes/functions/ - PHP functions and utilities
includes/config/ - Configuration files
Comment Your Include Files
Add descriptive comments at the top of each include file explaining its purpose and any variables it expects:
<?php
/**
* Site Header Template
*
* This file contains the header HTML and navigation for the site.
*
* @requires The following variables to be set before including:
* - $pageTitle: The title of the current page
* - $bodyClass: Optional CSS class for the body element
*/
// Default values for optional variables
$bodyClass = isset($bodyClass) ? $bodyClass : '';
?>
Workshop Exercise: Build a Simple PHP Website with Includes
Exercise: Create a Basic Website with Header and Footer
Let's apply what we've learned by creating a simple multi-page website with reusable components:
<?php
$pageTitle = "Home";
$currentPage = "home";
include 'includes/header.php';
?>
<h1>Welcome to My PHP Website</h1>
<p>This is a simple website built with PHP includes.</p>
<p>Navigate using the menu above to explore different pages.</p>
<?php include 'includes/footer.php'; ?>
Step 6: Create Additional Pages
Create about.php and contact.php following the same pattern:
<?php
$pageTitle = "About";
$currentPage = "about";
include 'includes/header.php';
?>
<h1>About Us</h1>
<p>This is the about page of our website.</p>
<p>Here you can learn more about our company and team.</p>
<?php include 'includes/footer.php'; ?>
PHP includes are a fundamental technique for creating modular, maintainable websites. By separating your code into reusable components, you can:
Eliminate repetition and redundancy
Simplify maintenance by centralizing common elements
Create a more organized and readable codebase
Make your website more consistent across pages
As you progress in your PHP and WordPress development journey, these include techniques will form the foundation of more advanced modular programming patterns like templating systems, components, and object-oriented structures.
Next Steps
In our next session, we'll be working on our mini-project, building a complete static website that incorporates everything we've learned in Module 1, including HTML structure, CSS styling, JavaScript interactivity, and PHP includes for modular code organization.