include, require, include_once, & require_onceFile inclusion directives allow modular PHP application code by importing external layout headers, footers, database configuration files, and functions into a running script.
| Directive | Missing File Behavior | Duplicate Guard | Use Case |
|---|---|---|---|
include |
Warning (E_WARNING); Script continues |
No | Optional UI partials (sidebars, banners) |
require |
Fatal Error (E_COMPILE_ERROR); Script halts |
No | Essential files (DB config, ORM, security) |
include_once |
Warning; Script continues | Yes | Functions, helper partials |
require_once |
Fatal Error; Script halts | Yes | Classes, core bootstrap, autoloaders |
flowchart TD
A["index.php (Entry point)"] --> B["require_once __DIR__ . '/config.php'"]
A --> C["include __DIR__ . '/header.php'"]
A --> D["Main Page Content Execution"]
A --> E["include __DIR__ . '/footer.php'"]
B -- Missing File --> F["Fatal Error: Execution Halts Immediately"]
C -- Missing File --> G["Warning: Render Page Without Header"]
<?php
declare(strict_types=1);
// 1. Mandatory Core Configuration (Script aborts if missing)
require_once __DIR__ . '/config.php';
$pageTitle = "Dashboard Overview";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= htmlspecialchars($pageTitle) ?></title>
</head>
<body style="font-family: system-ui, sans-serif; background: #0f172a; color: #f8fafc; padding: 2rem;">
<!-- 2. Optional UI Partial Header -->
<?php include __DIR__ . '/partials/header.php'; ?>
<main>
<h1>Welcome to <?= APP_NAME ?></h1>
<p>Main application dashboard content goes here.</p>
</main>
<!-- 3. Optional UI Partial Footer -->
<?php include __DIR__ . '/partials/footer.php'; ?>
</body>
</html>
__DIR__: Write require_once __DIR__ . '/file.php'; to avoid relative path resolution bugs when scripts are executed from different working directories.require_once for Libraries & Classes: Prevents redeclaration fatal errors if a class file is imported multiple times.include for View Partials: Ensures that missing non-critical UI components (like a promotional banner) do not crash the entire website.Write a line of code using require_once and __DIR__ to safely import a database connection file located in ../config/database.php!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.