include & require
A real website has many pages, and they all share the same header, menu, footer, database settings and helper functions. Copying that code into every page means that one change to the phone number in the footer turns into twenty edits. PHP solves this by letting one file pull in another.
In this lesson you will learn the four ways to load a file (include, require, include_once and require_once), how they differ, how to build page templates from shared parts, and how to keep a config file that returns an array.
Loading one file from another
When PHP reaches a require statement, it reads the named file and runs it at that exact spot, as if you had pasted its code there. Here is a small helper file:
<?php
// helpers.php
function formatRupees(float $amount): string
{
return '₹' . number_format($amount, 2);
}Any page can now use the function:
<?php
declare(strict_types=1);
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/helpers.php'; // skipped: already loaded
echo formatRupees(1299) . "\n";₹1,299.00
The second require_once does nothing, because PHP remembers that it has already loaded helpers.php. With plain require, loading it twice would stop the script with Fatal error: Cannot redeclare function formatRupees(), because a function can only be defined once.
include or require?
The four statements differ in two ways: what happens when the file is missing, and whether a file can be loaded more than once.
| Statement | File missing | Loads the same file twice? |
|---|---|---|
include | Warning, the script continues | Yes |
require | Fatal error, the script stops | Yes |
include_once | Warning, the script continues | No, later calls are skipped |
require_once | Fatal error, the script stops | No, later calls are skipped |
Here is the difference in practice, with a file sidebar.php that does not exist:
<?php
include __DIR__ . '/partials/sidebar.php';
echo "After include\n";
require __DIR__ . '/partials/sidebar.php';
echo "After require\n";Warning: include(.../partials/sidebar.php): Failed to open stream: No such file or directory in ... on line 2 Warning: include(): Failed opening '.../partials/sidebar.php' for inclusion ... After include Warning: require(.../partials/sidebar.php): Failed to open stream: No such file or directory in ... on line 4 Fatal error: Uncaught Error: Failed opening required '.../partials/sidebar.php' ...
(The real messages show the full paths; they are shortened here.) After include fails, the script carries on and prints After include. After require fails, it stops, so After require never appears.
Which should you use? Almost always require or require_once. If a file your page depends on is missing, it is better to stop clearly than to carry on half-broken and show a page with no database or a missing function. Use require_once for files that define functions, classes or constants. Use require for template parts that you deliberately output more than once, such as a product card in a loop.
Always build the path with __DIR__
Write require __DIR__ . '/helpers.php', not require 'helpers.php'. A bare relative path is searched using the include_path setting and the current working directory, which can differ between the browser, the command line and a cron job. __DIR__ is always the folder of the file you are writing in, so the path works everywhere. To reach a parent folder, use __DIR__ . '/../config/app.php'.
A config file that returns an array
An included file can return a value, and require hands that value back to you. This is the cleanest way to keep settings in one place:
<?php
// config/app.php
return [
'site_name' => 'Jaipur Sweets',
'phone' => '+91 98765 43210',
'gst_rate' => 0.05,
];<?php
declare(strict_types=1);
$config = require __DIR__ . '/config/app.php';
echo $config['site_name'] . "\n";
echo 'GST: ' . ($config['gst_rate'] * 100) . "%\n";Jaipur Sweets GST: 5%
Because the settings live in a variable, nothing leaks into other files by accident. Keep files with passwords, such as database settings, outside the web root so no URL can reach them. You will do exactly that in Connecting to MySQL with PDO.
Building pages from shared parts
An included file shares the variables of the code around it. That makes it easy to build pages from a header and a footer. The parts are usually called partials.
<!-- partials/header.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= htmlspecialchars($pageTitle) ?> | <?= htmlspecialchars($config['site_name']) ?></title>
</head>
<body>
<header><strong><?= htmlspecialchars($config['site_name']) ?></strong></header><!-- partials/footer.php -->
<footer>Call us: <?= htmlspecialchars($config['phone']) ?></footer>
</body>
</html>Each page sets its own variables and then loads the parts:
<?php
declare(strict_types=1);
$config = require __DIR__ . '/config/app.php';
$pageTitle = 'Home';
require __DIR__ . '/partials/header.php';
?>
<main>
<h1>Fresh sweets every morning</h1>
</main>
<?php require __DIR__ . '/partials/footer.php'; ?>The browser receives one complete page:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Home | Jaipur Sweets</title> </head> <body> <header><strong>Jaipur Sweets</strong></header> <main> <h1>Fresh sweets every morning</h1> </main> <footer>Call us: +91 98765 43210</footer> </body> </html>
<?= ... ?> is the short echo tag: <?= $x ?> means <?php echo $x; ?>. Now changing the phone number means editing one line in config/app.php.
Where autoloading takes over
In object-oriented code, you write one class per file. Writing a require_once line for every class quickly gets tiring. Composer's autoloader loads class files automatically the first time a class is used, so modern projects need just one line, require __DIR__ . '/vendor/autoload.php';. You will set this up in Namespaces & Composer.
Common mistakes
- Relative paths without
__DIR__. The page works in the browser and breaks in a cron job. Always start with__DIR__. - Using
includefor files the page cannot work without. Userequireso a missing file stops the script clearly. - Loading a function file twice with
require. Userequire_oncefor files that define functions or classes. - Output in a config or helper file. A stray blank line after
?>sends output beforeheader()orsession_start(). Leave out the closing?>in files that contain only PHP.
Key points
includeandrequirerun another file at that spot, sharing the current variables.- A missing file gives a warning with
includeand a fatal error withrequire. - The
_onceversions skip a file that is already loaded; use them for functions and classes. - Build every path with
__DIR__so it works from any working directory. - An included file can
returna value, which is ideal for config arrays. - Never build an include path from user input.
Exercise
Create a small two-page site. Put the site name and a list of menu links (Home to index.php, Contact to contact.php) in config/app.php. Write partials/header.php that prints the page title and the menu from the config, and use it on both index.php and contact.php.
Show solution
<?php
// config/app.php
return [
'site_name' => 'Rohtak Book Store',
'menu' => ['Home' => 'index.php', 'Contact' => 'contact.php'],
];<!-- partials/header.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= htmlspecialchars($pageTitle) ?> | <?= htmlspecialchars($config['site_name']) ?></title>
</head>
<body>
<nav>
<?php foreach ($config['menu'] as $label => $url): ?>
<a href="<?= htmlspecialchars($url) ?>"><?= htmlspecialchars($label) ?></a>
<?php endforeach; ?>
</nav><?php
// contact.php (index.php is the same with a different title and content)
declare(strict_types=1);
$config = require __DIR__ . '/config/app.php';
$pageTitle = 'Contact';
require __DIR__ . '/partials/header.php';
?>
<main><p>Call us on +91 98765 43210.</p></main>
</body>
</html>Both pages share one header, so adding a menu link means editing only the config array.
Quick Quiz
1. What happens when require cannot find the file?
require treats a missing file as a fatal error; include only warns.
2. Which statement should you use to load a file that defines functions?
require_once stops the script if the file is missing and never loads it twice, so the functions are not redeclared.
3. What does $config = require __DIR__ . '/config/app.php'; store in $config?
An included file can return a value, and require gives that value back.
4. Why write __DIR__ . '/helpers.php' instead of 'helpers.php'?
__DIR__ is the folder of the current file, so the path works from the browser, the command line and cron.
Learn PHP with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
