The include and require statements insert the code from one PHP file into another before execution continues. Splitting shared navigation bars, configuration loaders, and helper functions into separate files removes copy-pasted code across pages.
include vs require vs _once VariantsChoose between include and require based on whether your application can safely continue if the target file is missing.
| Statement | Missing File Behavior | Prevents Duplicate Loads |
|---|---|---|
include |
Emits warning and continues | No |
require |
Throws fatal Error and stops |
No |
include_once |
Emits warning and continues | Yes |
require_once |
Throws fatal Error and stops |
Yes |
Use require_once for database configs, helper functions, and Composer's vendor/autoload.php. Use include for optional view partials like promotional banners or footer widgets.
<?php
declare(strict_types=1);
// Always anchor paths with __DIR__ so working directory changes cannot break loads
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/helpers/formatting.php';
$pageTitle = "Dashboard";
include __DIR__ . '/partials/header.php';
?>
<main>
<h2>Account Overview</h2>
<p>Welcome back to your workspace.</p>
</main>
<?php include __DIR__ . '/partials/footer.php'; ?>
An included file inherits all variables available at the exact line where include or require appears. Wrapping view rendering inside a small helper function prevents partial templates from leaking temporary variables into global scope.
include 'header.php': Relative paths depend on the caller's working directory and fail when running cron scripts or nested routes. Always prefix with __DIR__ . '/'.include $_GET['page'] . '.php': Unvalidated paths cause Local File Inclusion (LFI) security vulnerabilities. Map route names using an explicit allowlist or match._once on function files: Including a file defining formatPrice() twice throws a fatal "Cannot redeclare function" error.return statement?Returning a value from an included PHP file passes that value directly back to the caller, such as $config = require __DIR__ . '/config.php';.
require for every class file?No. Modern PHP projects load classes automatically with Composer's PSR-4 autoloader, requiring only a single require __DIR__ . '/vendor/autoload.php'; at entry.
require_once hurt performance?No. PHP's OPcache tracks loaded file paths in memory, so _once checks add negligible overhead.
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.