Include Files
What are Partial Files?
Section titled “What are Partial Files?”Partial files let you split your code into reusable pieces. Instead of repeating the same code (like headers, footers, or database connections), you write it once and include it where needed.
project/├── includes/│ ├── header.php│ ├── footer.php│ └── db.php├── index.php└── about.phpThe Four Include Functions
Section titled “The Four Include Functions”include
Section titled “include”Includes a file. Shows a warning if the file is not found, but continues execution.
include 'header.php';echo "Page content"; // This still runs even if header.php is missingrequire
Section titled “require”Includes a file. Shows a fatal error if the file is not found and stops execution.
require 'db.php';echo "This won't run if db.php is missing";include_once
Section titled “include_once”Same as include, but only includes the file once. Prevents duplicate inclusions.
include_once 'functions.php';include_once 'functions.php'; // Ignored - already includedrequire_once
Section titled “require_once”Same as require, but only includes the file once.
require_once 'db.php';require_once 'db.php'; // Ignored - already includedWhen to Use Which
Section titled “When to Use Which”| Function | If file missing | Multiple includes |
|---|---|---|
include | Warning (continues) | Allowed |
require | Fatal error (stops) | Allowed |
include_once | Warning (continues) | Once only |
require_once | Fatal error (stops) | Once only |
General rule:
- Use
requirefor essential files (database, config) - Use
includefor optional files (sidebar, widgets) - Use
_oncevariants for files with function/class definitions
Example
Section titled “Example”includes/header.php
<!DOCTYPE html><html><head> <title><?= $pageTitle ?? 'My Site' ?></title></head><body> <nav>Site Navigation</nav>includes/footer.php
<footer>© 2024 My Site</footer></body></html>index.php
<?php$pageTitle = "Home";require 'includes/header.php';?>
<h1>Welcome to the homepage</h1><p>Page content goes here.</p>
<?php require 'includes/footer.php'; ?>Output: A complete HTML page with header, content, and footer.