Explain it simply
Include and require in plain language
include and require let one PHP file borrow another. Instead of pasting the same navigation menu into thirty pages, you write it once in menu.php and put a single line in each page that says 'place that file here'. When you change the menu, every page changes with it.
It works like a recipe that says 'make the sauce from card 7': you do not copy the card into the recipe, you just point at it. When PHP reaches that line it reads the file you named and runs it right there.
Problem → Why → Solution
The problem: copied code and vanished files
Suppose thirty pages each contain their own copy of the header. When the logo changes, one person updates twenty-seven and forgets three. Once you start using include to avoid that, a new set of problems appears: a page that loads a helper-function file twice dies with the fatal error Cannot redeclare money(), and a config file pulled in with include on a wrong path only produces a warning while the rest of the page carries on without any database settings.
Sharing files needs rules: how a file is found, what happens when it is missing, and how to stop it loading twice.
<?php
include 'config.php'; // wrong path? only a warning, the page keeps going
include 'helpers.php';
include 'helpers.php'; // pasted from another page: declares money() twice
echo money($price); // Fatal error: Cannot redeclare money()Why there are four statements
Files differ in importance and in nature. A page cannot work without its database config, so a missing config should stop things loudly and early, while a decorative banner can safely be skipped. A file that declares functions cannot be loaded twice, so it needs a 'once only' rule. include, require and the _once forms encode those rules, and your job is to pick the one that matches the file.
Core concept: run that file right here
include and require read another PHP file and run its code right where the statement sits, as if it had been pasted there. This is how a header, a footer, a config array or a set of helper functions is shared by many pages without copying. Any HTML outside the PHP tags in that file is sent to the output at that point, too.
There are four statements. include and require differ in what happens when the file cannot be found or read: include raises a warning, returns false and carries on, while require raises the warning and then throws an Error, which ends the script unless you catch it. The _once forms remember every file they have loaded (by its resolved path) and skip a second request, returning true. Use them for files that declare functions or classes, because declaring the same function twice is a fatal error.
Pick by importance. If the page cannot work without the file (database config, the autoloader, a set of functions), use require_once or require, because a failure should be loud and early. If the file is optional decoration, include is acceptable, but check its return value when you rely on the result.
The included code runs in the variable scope of the line that included it. Include from the top of a script and its variables become globals; include inside a function and they stay local to that function. A file can also return a value, and include or require hands it back, so a config file that returns an array is much tidier than one that sets global variables.
Finally, build paths from the file's own location with __DIR__. A bare 'config.php' is searched through the include_path and other places, and a path starting with ./ depends on the directory the script was launched from, which works on your laptop and breaks under cron.
- The statement runs at its own line
- PHP finds the file from its path
- The file runs in the caller's scope
- Output or a return value comes back
If the file is missing, include gives false and carries on, while require throws an Error.
General pattern
require_once __DIR__ . '/path/to/file.php'; // must exist, load once
require __DIR__ . '/path/to/file.php'; // must exist, load every time
include __DIR__ . '/path/to/partial.php'; // optional, load every time
include_once __DIR__ . '/path/to/optional.php'; // optional, load once
$value = require __DIR__ . '/path/to/config.php'; // file ends with: return ...;Use the require forms when the page cannot work without the file, choose _once for files that declare functions or classes, and start every path from __DIR__.
Worked example: config, helpers and a template in three files
The command line has no project folder, so this sample creates three files (config.php, helpers.php and header.php) in a temporary directory itself, then uses include and require on them. The files are deleted at the end, so nothing is left behind, and the output deliberately contains no absolute paths.
<?php
$dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'inc_' . bin2hex(random_bytes(4));
mkdir($dir);
file_put_contents($dir . '/config.php', <<<'FILE'
<?php
return ['site' => 'Tea Shop', 'currency' => 'MMK'];
FILE);
file_put_contents($dir . '/helpers.php', <<<'FILE'
<?php
function money(int $amount): string
{
return number_format($amount) . ' MMK';
}
FILE);
file_put_contents($dir . '/header.php', <<<'FILE'
<h1><?= htmlspecialchars($title) ?></h1>
FILE);
$config = require $dir . '/config.php';
echo 'site: ', $config['site'], "\n";
require_once $dir . '/helpers.php';
$again = require_once $dir . '/helpers.php';
echo 'second require_once returned: ', var_export($again, true), "\n";
echo money(2500), "\n";
$title = 'Welcome';
include $dir . '/header.php';
echo "\n";
$warnings = [];
set_error_handler(function (int $level, string $message) use (&$warnings): bool {
if (preg_match('/Failed to open stream: (.+)$/', $message, $match)) {
$warnings[] = $match[1];
}
return true;
});
$result = include $dir . '/missing.php';
restore_error_handler();
echo 'missing file, include returned: ', var_export($result, true), "\n";
echo 'warning text: ', $warnings[0] ?? '(none)', "\n";
array_map('unlink', glob($dir . '/*.php'));
rmdir($dir);Code breakdown
- A config file that returns
$config = require $dir . '/config.php';config.php ends with return ['site' => ...], so require hands that array back. No global variable appears, and you choose the name that receives the result.
- Load a function file once
$again = require_once $dir . '/helpers.php';The second require_once does not run the file again, so there is no redeclaration error for money(). The value it returns is true.
- The included file sees your variable
$title = 'Welcome';header.php never defines $title; it uses the variable that exists in the scope of the include line. That is why $title is assigned before the include runs.
- Catch the warning text
if (preg_match('/Failed to open stream: (.+)$/', $message, $match)) {include raises a warning for a missing file, and that text normally contains the full path, so an error handler catches it and keeps only the 'No such file or directory' part.
- Inspect the return value
$result = include $dir . '/missing.php';For a missing file include returns false and the script keeps running. For optional files you can test that false and decide what to do.
site: Tea Shop
second require_once returned: true
2,500 MMK
<h1>Welcome</h1>
missing file, include returned: false
warning text: No such file or directoryinclude versus require when the file is missing
| Statement | File missing | Already loaded earlier |
|---|---|---|
| include | warning, returns false, script continues | loads it again |
| require | warning, then throws Error; uncaught it stops the script | loads it again |
| include_once | warning, returns false, script continues | skips it and returns true |
| require_once | same as require | skips it and returns true |
Let us see this for ourselves. The script below calls a file that does not exist with both include and require. The warning text contains a path, so an error handler swallows it. In PHP 8 the result of a failed require is an Error exception, which try/catch can catch. Left uncaught, the script ends with 'Fatal error: Uncaught Error: Failed opening required ...'.
<?php
$name = 'nope_' . bin2hex(random_bytes(4)) . '.php';
$missing = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $name;
set_error_handler(function (int $level): bool {
return true; // swallow the warning so the output stays tidy
});
$value = include $missing;
echo 'include -> returned ', var_export($value, true), ', script continues', "\n";
try {
require $missing;
} catch (Error $e) {
echo 'require -> threw ', get_class($e), ', an uncaught one would stop here', "\n";
}
restore_error_handler();include -> returned false, script continues
require -> threw Error, an uncaught one would stop hereAn included file runs in the caller's scope
This is the foundation of templates. In the example below greeting.php never declares $name; it reads the $name that exists inside the render() function. Because include is called inside the function, the $message it defines is a local variable of render() and does not leak into the global scope. Calling templates from a function is therefore a way to control where their variables live.
<?php
$dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'scope_' . bin2hex(random_bytes(4));
mkdir($dir);
file_put_contents($dir . '/greeting.php', <<<'FILE'
<?php
$message = "Hello, $name!";
FILE);
function render(string $dir, string $name): string
{
include $dir . '/greeting.php'; // runs inside render()'s scope
return $message;
}
echo render($dir, 'Ada'), "\n";
echo 'leaked into the global scope: ', var_export(isset($message), true), "\n";
unlink($dir . '/greeting.php');
rmdir($dir);Hello, Ada!
leaked into the global scope: falseWhy paths should start from __DIR__
A bare path such as 'config/app.php' is searched in each include_path entry, then in the directory of the calling script, then in the current working directory. A path starting with ./ or ../ is compared with the current working directory only, and for a command-line run that is the folder you launched php from, which can differ from the file's own folder. __DIR__ always gives the folder of the file containing that line, so it works wherever you run it from.
<?php
// Fragile: depends on include_path and on where the script was launched from
require 'config/app.php';
require './config/app.php';
// Reliable: always relative to THIS file
require __DIR__ . '/config/app.php';
require dirname(__DIR__) . '/vendor/autoload.php';Never let a visitor choose the path
A line like include $_GET['page'] . '.php'; is convenient and it is also an open door. A visitor who sends a path containing ../ can run PHP files you never meant to expose, and combined with any other weakness that lets files be written, the damage grows. This is called Local File Inclusion. Including remote URLs (allow_url_include) is off by default, but local files stay dangerous.
The fix is to treat what the visitor sends as nothing more than a key into an allow-list. Only when the key exists in the list do you use the file name that you wrote yourself.
<?php
$pages = [
'home' => 'home.php',
'about' => 'about.php',
'contact' => 'contact.php',
];
foreach (['about', '../../etc/passwd', 'HOME', 'contact'] as $requested) {
if (array_key_exists($requested, $pages)) {
echo str_pad($requested, 18), 'include ', $pages[$requested], "\n";
} else {
echo str_pad($requested, 18), 'rejected, falling back to home.php', "\n";
}
}about include about.php
../../etc/passwd rejected, falling back to home.php
HOME rejected, falling back to home.php
contact include contact.phpIn real projects
include and require in real projects
On small websites the layout is split into partial files (header.php, footer.php, menu.php) that every page includes. At the top of an application's front controller (index.php) you will usually find require __DIR__ . '/../vendor/autoload.php'; and a require of the config file. WordPress themes wrap the same idea in functions such as get_header().
As a project grows you stop writing require_once for every class, because an autoloader loads those files for you (the next lesson covers it). Bootstrap files, config files and templates still rely on include and require, so these rules stay relevant.
- Layout partials: every page includes header.php, footer.php and menu.php, so a change is made in one place.
- Bootstrap and config: the front controller requires the autoloader and the config array and stops immediately if either is missing.
- Page routing: the ?page= value is matched against an allow-list and only the matching template is included.
Common mistakes
Common mistakes with include and require
Using include for a file the page cannot live without
If config.php is pulled in with include and the path is wrong, a single warning appears and the page carries on without database settings, failing later with confusing errors. Use require for files that must exist.
Loading a function file without _once
When two files include helpers.php, you get the fatal error Cannot redeclare money(). Use require_once for files that declare functions or classes.
Relative paths that depend on the working directory
require './config/app.php'; may work in the browser and break when cron or the command line runs the script from another folder. Anchor the path with __DIR__.
Using visitor-supplied text as a path
include $_GET['page'] . '.php'; can run files you never intended. Do not trust filters such as str_replace('..', '', ...); use an allow-list.
Stray whitespace causing headers already sent
A blank line before <?php, or a newline after ?>, in an included file is sent as output, and a later header() or session_start() then warns 'Cannot modify header information - headers already sent'. Leave the closing ?> off files that contain only PHP.
Best practices
Best practices
- Use the require forms for files you cannot live without and the include forms for optional partials.
- Load every file that declares functions or classes with _once, or use an autoloader.
- Start every path from __DIR__ and never trust the working directory.
- Let a config file return an array instead of setting global variables.
Mini challenge
Mini challenge: a safe config loader
Write loadConfig(string $dir, string $name): array. It validates $name against a pattern, requires the file from $dir, and returns the array that file returns. Every failure case must throw a clear exception.
- $name may contain only a-z and underscores (otherwise InvalidArgumentException)
- A missing file throws RuntimeException
- A file that returns something other than an array throws UnexpectedValueException
- In a temp directory create app.php (an array) and bad.php (a string), try app, bad, missing and ../app, print the results, and delete the files at the end
<?php
function loadConfig(string $dir, string $name): array
{
// TODO: reject names that are not lowercase letters and underscores
// TODO: build the path from $dir and $name (never from anything else)
// TODO: throw RuntimeException when the file does not exist
// TODO: require the file and check that it returned an array
}
$dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'cfg_' . bin2hex(random_bytes(4));
mkdir($dir);
// TODO: write app.php (returns ['name' => 'Tea Shop', 'debug' => true]) and bad.php
// TODO: try loadConfig for 'app', 'bad', 'missing' and '../app'; print each outcome
// TODO: delete the files and the directoryExpected: app prints Tea Shop with debug on, bad reports an UnexpectedValueException, missing a RuntimeException and ../app an InvalidArgumentException, each with its message.
Show hint
Check preg_match('/^[a-z_]+$/D', $name) first, then use is_file() before require. For the test files, write lines like '<?php return ...;' with file_put_contents.
Show solution
<?php
function loadConfig(string $dir, string $name): array
{
if (preg_match('/^[a-z_]+$/D', $name) !== 1) {
throw new InvalidArgumentException('invalid config name');
}
$path = $dir . DIRECTORY_SEPARATOR . $name . '.php';
if (!is_file($path)) {
throw new RuntimeException("config '$name' not found");
}
$config = require $path;
if (!is_array($config)) {
throw new UnexpectedValueException("$name.php must return an array");
}
return $config;
}
$dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'cfg_' . bin2hex(random_bytes(4));
mkdir($dir);
$app = "<?php\nreturn ['name' => 'Tea Shop', 'debug' => true];\n";
file_put_contents($dir . '/app.php', $app);
file_put_contents($dir . '/bad.php', "<?php\nreturn 'oops';\n");
foreach (['app', 'bad', 'missing', '../app'] as $name) {
try {
$config = loadConfig($dir, $name);
$mode = $config['debug'] ? 'on' : 'off';
echo "$name: {$config['name']} (debug $mode)\n";
} catch (Exception $e) {
echo "$name: ", get_class($e), ': ', $e->getMessage(), "\n";
}
}
array_map('unlink', glob($dir . '/*.php'));
rmdir($dir);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- include warns and returns false for a missing file while require throws an Error, so choose by how important the file is.
- The _once forms skip a repeat load and return true, which suits files that declare functions or classes.
- Included code runs in the caller's scope and can return a value, so a config file that returns an array is tidy.
- Start paths from __DIR__, and never use visitor-supplied text as a path; choose through an allow-list.
PHP Language Reference — PHP Documentation Group