PHP Include & Require

Splitting code across files keeps headers, footers, and config in one place.

PHP
<?php
  include 'header.php';
  require 'config.php';
  include_once 'helpers.php';
  require_once 'db.php';

include vs require

On failure
include Warning, script continues
require Fatal error, script stops

Use require for anything the page cannot work without (config, database connection) and include for optional pieces.

The _once variants

include_once / require_once skip the file if it's already been loaded — essential for files that define functions or classes, since defining the same function twice is a fatal error.

A typical layout

PHP
<?php
// header.php
?>
<!DOCTYPE html>
<html>
<head><title><?= htmlspecialchars($pageTitle ?? 'Scolar') ?></title></head>
<body>
<nav>...</nav>
PHP
<?php
// page.php
$pageTitle = 'Books';
require __DIR__ . '/header.php';
?>
<h1>Our books</h1>
<?php require __DIR__ . '/footer.php'; ?>

Always use __DIR__

A relative path like require 'config.php' is resolved against the calling script's directory, which breaks as soon as the file is included from somewhere else. __DIR__ is always the directory of the file the code is written in:

PHP
<?php
  require __DIR__ . '/../config/database.php';  // reliable
  // require '../config/database.php';          // fragile

Included files share scope

Variables defined before the include are visible inside it, and variables the included file defines are visible after it. That is convenient but makes it easy to lose track of where a variable came from — one more reason to prefer functions and classes over long included scripts.