Split your site into reusable files with include and require, a clear project structure, and centralized constants.
Open this lesson in KodokonAs soon as your site grows beyond two pages, duplicating the header, footer, and functions in every file becomes unmanageable. PHP provides four inclusion statements: include, require, and their include_once / require_once variants. They all insert the contents of a file at the point of the call; the difference lies in error handling and repeated inclusions. The _once variants keep track of already-loaded files and include them only once - essential for function files, which cannot be redeclared.
<?php
declare(strict_types=1);
function e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES);
}
function formatPrice(float $amount): string
{
return number_format($amount, 2, '.', ',') . ' €';
}A clear project structure is worth a thousand comments. A common convention: public/ holds the pages served to the browser (it's the only exposed folder), src/ gathers configuration and functions, templates/ contains page fragments (header.php, footer.php). PHP's built-in development server is launched by pointing it at public/.
mkdir -p my-site/public my-site/src
mkdir -p my-site/templates
cd my-site
php -S localhost:8000 -t publicThe project's fixed values (site name, paths, settings) deserve constants rather than variables: they can't be overwritten by accident. const is resolved at compile time, define() at runtime; in practice, prefer const in your configuration files. For paths, always prefix with __DIR__, the folder of the current file: your inclusions will work no matter where the script is launched from.
<?php
declare(strict_types=1);
const SITE_NAME = 'La Bonne Pizza';
const ITEMS_PER_PAGE = 12;
const UPLOAD_DIR = __DIR__ . '/../public/uploads';
define('BASE_URL', 'http://localhost:8000');Each page then becomes a short assembly: load the configuration and functions with require, then include the templates around the specific content.
<?php
require __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/functions.php';
$pageTitle = SITE_NAME . ' - Home';
include __DIR__ . '/../templates/header.php';
?>
<main>
<h1><?= e($pageTitle) ?></h1>
<p>Pizza of the day: <?= formatPrice(9.5) ?></p>
</main>
<?php include __DIR__ . '/../templates/footer.php'; ?>