Skip to main content

Course Progress

Loading...

Basic PHP Includes for Header and Footer

Duration: 45 minutes
Module 1: Introduction to PHP

Learning Objectives

  • Understand PHP basics
  • Set up PHP development environment
  • Write server-side code
  • Prepare for WordPress development

Understanding PHP Includes

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: Code Duplication Website with Multiple Pages Page 1 Header Code (Duplicated) Page 1 Content Footer Code (Duplicated) Page 2 Header Code (Duplicated) Page 2 Content Footer Code (Duplicated) Page 3 Header Code (Duplicated) Page 3 Content Footer Code (Duplicated) !

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: Code Reusability header.php All Header Code footer.php All Footer Code Page 1 include 'header.php' Page 1 Content include 'footer.php' Page 2 include 'header.php' Page 2 Content include 'footer.php' Page 3 include 'header.php' Page 3 Content include 'footer.php'

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

PHP Include Processing Sequence Browser PHP Processor PHP Page Included File Request page.php Process page.php PHP encounters include statement Request included file File content inserted PHP continues processing combined code Complete processed output Send HTML response

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:

my_website/
├── includes/
│   ├── header.php
│   ├── footer.php
│   └── navigation.php
├── css/
│   └── style.css
├── js/
│   └── script.js
├── images/
├── index.php
├── about.php
├── services.php
└── contact.php

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:

includes/header.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - My Website</title>
    <link rel="stylesheet" href="/css/style.css">
    <link rel="icon" href="/favicon.png">
    <script src="/js/script.js" defer></script>
</head>
<body>
    <header class="site-header">
        <div class="container">
            <div class="logo">
                <a href="index.php">My Website</a>
            </div>
            <?php include 'includes/navigation.php'; ?>
        </div>
    </header>
    
    <main class="site-content">
        <div class="container">
            <h1><?php echo $pageTitle; ?></h1>

Notice several important elements in our header file:

  • We're using PHP to dynamically set the page title with $pageTitle variable
  • We're including common CSS and JavaScript files
  • We've included a navigation component (which we'll create next)
  • The file doesn't have a closing </body> or </html> tag - these will be in the footer
  • We've opened the main content container that will be closed in the footer

Step 3: Creating the Navigation File

Let's create a separate navigation file that we include within our header:

includes/navigation.php

<nav class="main-nav">
    <ul>
        <li<?php if($currentPage == 'home') echo ' class="active"'; ?>>
            <a href="index.php">Home</a>
        </li>
        <li<?php if($currentPage == 'about') echo ' class="active"'; ?>>
            <a href="about.php">About Us</a>
        </li>
        <li<?php if($currentPage == 'services') echo ' class="active"'; ?>>
            <a href="services.php">Services</a>
        </li>
        <li<?php if($currentPage == 'contact') echo ' class="active"'; ?>>
            <a href="contact.php">Contact</a>
        </li>
    </ul>
</nav>

Our navigation file includes:

  • A basic navigation menu structure
  • Dynamic class assignment based on the current page (using the $currentPage variable)
  • This allows us to highlight the current page in our navigation

Step 4: Creating the Footer File

Now let's create our footer that will close the HTML structure:

includes/footer.php

        </div><!-- Close .container from header -->
    </main><!-- Close .site-content from header -->
    
    <footer class="site-footer">
        <div class="container">
            <div class="footer-content">
                <div class="footer-col">
                    <h3>About Us</h3>
                    <p>A brief description of your company or website.</p>
                </div>
                
                <div class="footer-col">
                    <h3>Quick Links</h3>
                    <ul>
                        <li><a href="index.php">Home</a></li>
                        <li><a href="about.php">About</a></li>
                        <li><a href="services.php">Services</a></li>
                        <li><a href="contact.php">Contact</a></li>
                    </ul>
                </div>
                
                <div class="footer-col">
                    <h3>Contact Info</h3>
                    <p>Email: info@example.com</p>
                    <p>Phone: (123) 456-7890</p>
                </div>
            </div>
            
            <div class="copyright">
                <p>&copy; <?php echo date("Y"); ?> My Website. All Rights Reserved.</p>
            </div>
        </div>
    </footer>

    <?php if(isset($pageSpecificScripts)): ?>
        <?php echo $pageSpecificScripts; ?>
    <?php endif; ?>
    
</body>
</html>

Our footer file:

  • 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.

Variable Scope in PHP Includes parent.php included.php $variable1 = "Hello"; include 'included.php'; echo $variable1; // "Hello" $variable2 = "World"; Return to parent echo $variable2; // "World"

Example: Sharing Configuration Variables

<?php
// config.php
$siteName = "My Awesome Website";
$siteEmail = "contact@example.com";
$siteTheme = "light";
$siteLanguage = "en";

// Database connection settings
$dbHost = "localhost";
$dbUser = "username";
$dbPass = "password";
$dbName = "mydatabase";
?>
<?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
// db_connect.php
function connectToDatabase() {
    static $connection;
    
    if (!isset($connection)) {
        $connection = mysqli_connect('localhost', 'username', 'password', 'database');
        
        if (!$connection) {
            die('Database Connection Failed: ' . mysqli_connect_error());
        }
    }
    
    return $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.

WordPress Template Hierarchy WordPress Page Request Page Type? single.php page.php category.php archive.php home.php/index.php index.php header.php footer.php Single Post Page Category Archive Home Not Found All templates include these

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:

Example: Creating Reusable Content Blocks

<!-- template-parts/content.php -->
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <header class="entry-header">
        <?php the_title('<h1 class="entry-title">', '</h1>'); ?>
    </header>
    
    <div class="entry-content">
        <?php the_content(); ?>
    </div>
</article>
<!-- template-parts/content-page.php -->
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <header class="entry-header">
        <?php the_title('<h1 class="entry-title">', '</h1>'); ?>
    </header>
    
    <div class="entry-content">
        <?php the_content(); ?>
        
        <?php
        // If we have page links (for paginated content)
        wp_link_pages([
            'before' => '<div class="page-links">Pages:</div>',
            'after'  => '',
        ]);
        ?>
    </div>
</article>

Using Template Parts in Different Templates

<?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!
?>

Safer Alternative:

<?php
// Safe approach - whitelist allowed values
$allowed_pages = ['home', 'about', 'contact', 'services'];
$page = isset($_GET['page']) ? $_GET['page'] : 'home';

if (in_array($page, $allowed_pages)) {
    include 'pages/' . $page . '.php';
} else {
    include 'pages/404.php';
}
?>

Use Absolute Paths When Possible

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:

  1. Step 1: Create Directory Structure

    Set up the following directory structure:

    my_website/
    ├── includes/
    │   ├── header.php
    │   ├── footer.php
    │   └── nav.php
    ├── css/
    │   └── style.css
    ├── index.php
    ├── about.php
    └── contact.php
  2. Step 2: Create the Header (includes/header.php)

    Create a header file with dynamic title and navigation:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?php echo $pageTitle; ?> - My PHP Website</title>
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>
        <header>
            <div class="logo">My PHP Website</div>
            <?php include 'includes/nav.php'; ?>
        </header>
        
        <main>
  3. Step 3: Create the Navigation (includes/nav.php)

    Create a navigation menu with active state:

    <nav>
        <ul>
            <li<?php if($currentPage == 'home') echo ' class="active"'; ?>>
                <a href="index.php">Home</a>
            </li>
            <li<?php if($currentPage == 'about') echo ' class="active"'; ?>>
                <a href="about.php">About</a>
            </li>
            <li<?php if($currentPage == 'contact') echo ' class="active"'; ?>>
                <a href="contact.php">Contact</a>
            </li>
        </ul>
    </nav>
  4. Step 4: Create the Footer (includes/footer.php)

    Create a footer with copyright information:

        </main>
        
        <footer>
            <p>&copy; <?php echo date('Y'); ?> My PHP Website. All rights reserved.</p>
        </footer>
    </body>
    </html>
  5. Step 5: Create the Home Page (index.php)

    Create the home page using your includes:

    <?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'; ?>
  6. 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
    $pageTitle = "Contact";
    $currentPage = "contact";
    include 'includes/header.php';
    ?>
    
    <h1>Contact Us</h1>
    <p>This is the contact page of our website.</p>
    <form method="post" action="">
        <div>
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" required>
        </div>
        <div>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required>
        </div>
        <div>
            <label for="message">Message:</label>
            <textarea id="message" name="message" required></textarea>
        </div>
        <button type="submit">Send Message</button>
    </form>
    
    <?php include 'includes/footer.php'; ?>
  7. Step 7: Create Basic CSS (css/style.css)

    Add some basic styling to make your site presentable:

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    body {
        font-family: Arial, sans-serif;
        line-height: 1.6;
        color: #333;
        max-width: 1200px;
        margin: 0 auto;
        padding: 0 20px;
    }
    
    header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px 0;
        border-bottom: 1px solid #ddd;
        margin-bottom: 30px;
    }
    
    .logo {
        font-size: 24px;
        font-weight: bold;
    }
    
    nav ul {
        display: flex;
        list-style: none;
    }
    
    nav ul li {
        margin-left: 20px;
    }
    
    nav ul li a {
        text-decoration: none;
        color: #333;
    }
    
    nav ul li.active a {
        color: #0066cc;
        font-weight: bold;
    }
    
    main {
        min-height: 70vh;
        padding-bottom: 40px;
    }
    
    h1 {
        margin-bottom: 20px;
    }
    
    p {
        margin-bottom: 15px;
    }
    
    footer {
        text-align: center;
        padding: 20px 0;
        border-top: 1px solid #ddd;
        margin-top: 20px;
    }
    
    /* Contact Form Styles */
    form {
        max-width: 600px;
        margin: 20px 0;
    }
    
    form div {
        margin-bottom: 15px;
    }
    
    label {
        display: block;
        margin-bottom: 5px;
    }
    
    input, textarea {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }
    
    textarea {
        height: 150px;
    }
    
    button {
        background: #0066cc;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 4px;
        cursor: pointer;
    }
    
    button:hover {
        background: #0052a3;
    }

Extension Challenges:

  1. Create a reusable sidebar component that can be included on certain pages
  2. Add a configuration file with site settings that's included on all pages
  3. Create a function to handle the active menu state more elegantly
  4. Add basic form processing to the contact page

Additional Resources

Conclusion

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.