Skip to content

Include 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.php

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 missing

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";

Same as include, but only includes the file once. Prevents duplicate inclusions.

include_once 'functions.php';
include_once 'functions.php'; // Ignored - already included

Same as require, but only includes the file once.

require_once 'db.php';
require_once 'db.php'; // Ignored - already included

FunctionIf file missingMultiple includes
includeWarning (continues)Allowed
requireFatal error (stops)Allowed
include_onceWarning (continues)Once only
require_onceFatal error (stops)Once only

General rule:

  • Use require for essential files (database, config)
  • Use include for optional files (sidebar, widgets)
  • Use _once variants for files with function/class definitions

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.