PHP Include & Require: Modular Web Architecture & Reusability

When developing websites with dozens of pages, copying and pasting the exact same navigation menu, header, database connection, and footer into every single file is disastrous for maintenance. If a link changes, you would have to edit 50 individual files! PHP solves this with modular file inclusion using include, require, include_once, and require_once.

The Critical Distinction: include vs require

Feature include Statement require Statement
Missing File Behavior Generates a Warning (E_WARNING). The rest of the page continues executing. Generates a Fatal Error (E_COMPILE_ERROR). The script halts immediately.
When to Use Non-critical display elements (e.g. sidebar widgets, footer text). Mission-critical files (e.g. database configs, authentication checks, functions).
<?php
    // If missing, script logs warning but continues
    include "footer.php";

    // If missing, script HALTS IMMEDIATELY with Fatal Error
    require "config/database.php";
?>

The "Once" Variations: include_once & require_once

If you accidentally include a file containing function definitions twice, PHP will crash with a fatal error: "Cannot redeclare function". The _once statements ensure that a file is imported only one single time, ignoring subsequent import attempts:

<?php
    // Safe: Prevents redeclaration crashes
    require_once __DIR__ . "/functions.php";
    require_once __DIR__ . "/functions.php"; // Silently skipped!
?>

Building a Modular Web Layout (Header, Content, Footer)

Here is how professional websites structure their pages cleanly:

<!-- index.php -->
<?php
    $pageTitle = "Home - Veewom Academy";
    require_once __DIR__ . "/includes/header.php";
?>

<main class="container">
    <h1>Welcome to the Student Portal</h1>
    <p>Explore the comprehensive PHP 8 curriculum.</p>
</main>

<?php
    require_once __DIR__ . "/includes/footer.php";
?>

BCA / CS University Exam Corner

High-Frequency Exam Question:

Q: Why should you avoid relative paths like require "../../db.php"?
A: Relative paths depend on the current working directory of the file being executed, which changes depending on which entry-point script loaded it. Using __DIR__ . '/db.php' resolves the absolute file system path, guaranteeing that includes never break regardless of directory nesting.

Interactive Student Practice Session

Exercise 32.1: Create a modular 3-file site: header.php, footer.php, and contact.php, dynamically passing the page title from contact to header.

Exercise 32.2: Write a script that intentionally attempts to include a non-existent file, observing how subsequent echo statements still execute.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!