PHP Including Files
Real PHP sites are split across many files: a header and footer shared by every page, a configuration file, a file full of helper functions, class files. PHP can pull the contents of one file into another with include and require, so you write shared code once and reuse it everywhere.
The four statements
| Statement | If the file is missing | Loads the same file twice? |
|---|---|---|
include 'file.php'; |
Warning, script continues | Yes |
require 'file.php'; |
Fatal error, script stops | Yes |
include_once 'file.php'; |
Warning, continues | No — skipped if already loaded |
require_once 'file.php'; |
Fatal error, stops | No — skipped if already loaded |
Rule of thumb: use require_once for code your page cannot work without (configuration, functions, classes) and include for optional pieces of output, such as a sidebar or a promotional banner.
A typical page layout
A small site might be organised like this:
site/
├── config.php settings (site name, database details)
├── functions.php helper functions
├── partials/
│ ├── header.php <html>, <head>, navigation
│ └── footer.php closing tags, copyright
└── about.php one page that includes the others<?php
// about.php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/functions.php';
$pageTitle = 'About us';
include __DIR__ . '/partials/header.php';
?>
<h1>About <?= e($siteName) ?></h1>
<p>We teach programming in the browser.</p>
<?php include __DIR__ . '/partials/footer.php'; ?>Tip: Build paths with
__DIR__(the folder of the current file). A bare relative path like'config.php'is resolved against the include path and the current working directory, which can change depending on how the script was started.
Variables are shared
An included file runs in the scope of the line that includes it. Variables defined before the include are visible inside the included file, and variables it creates are visible afterwards. That is how header.php can print $pageTitle.
The playgrounds run a single script, but PHP can still write a file and then include it. The next example creates a tiny greeting.php, includes it, and deletes it again:
<?php
file_put_contents('greeting.php', '<?php
$greeting = "Hello, $visitor!";
echo "Inside greeting.php" . PHP_EOL;
');
$visitor = 'Hoa';
include 'greeting.php'; // runs the file right here
echo $greeting . PHP_EOL; // variable created by the included file
unlink('greeting.php');Inside greeting.php
Hello, Hoa!
Returning values from a file
An included file can return a value, which becomes the result of the include expression. This is a popular way to write configuration files:
<?php
file_put_contents('settings.php', '<?php
return [
"site_name" => "TAD Market",
"per_page" => 20,
"debug" => false,
];
');
$config = require 'settings.php';
echo $config['site_name'] . " shows " . $config['per_page'] . " items per page" . PHP_EOL;
var_dump($config['debug']);
unlink('settings.php');TAD Market shows 20 items per page
bool(false)
include_once in action
Including a file with function definitions twice would fail with "Cannot redeclare function". The _once variants remember which files were already loaded and silently skip repeats:
<?php
file_put_contents('helpers.php', '<?php
echo "loading helpers" . PHP_EOL;
function shout(string $s): string { return strtoupper($s) . "!"; }
');
require_once 'helpers.php';
require_once 'helpers.php'; // skipped: already loaded
$result = include_once 'helpers.php'; // returns true when skipped
echo shout('done') . PHP_EOL;
var_dump($result);
unlink('helpers.php');loading helpers
DONE!
bool(true)
Autoloading classes
In modern projects you rarely write long lists of require lines for classes. Instead you register an autoloader — usually the one generated by Composer — and PHP loads a class file automatically the first time the class is used:
<?php
require __DIR__ . '/vendor/autoload.php'; // Composer's autoloader
$mailer = new App\Mail\Mailer(); // file loaded on demandYou will meet namespaces and autoloading again in the OOP section.
Note: Never include a file whose name comes from user input, such as
include $_GET['page'];. An attacker could make your server run files you never intended. Map allowed names to files with an array instead.
Test yourself
What happens when require cannot find the file?
- A warning, and the script continues
- A fatal error, and the script stops
- It returns
falsesilently - It creates an empty file
Which statement is best for loading a file of function definitions?
includerequirerequire_onceecho
$cfg = require 'config.php'; — what ends up in $cfg?
- Always
true - The file's contents as a string
- The value the file
returns - The file name