include & require

PHP · Lesson 22 of 37 8 min read Updated

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
<?php
// helpers.php
function formatRupees(float $amount): string
{
    return '₹' . number_format($amount, 2);
}

Any page can now use the function:

PHP
<?php
declare(strict_types=1);

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/helpers.php';   // skipped: already loaded

echo formatRupees(1299) . "\n";
Output
₹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.

StatementFile missingLoads the same file twice?
includeWarning, the script continuesYes
requireFatal error, the script stopsYes
include_onceWarning, the script continuesNo, later calls are skipped
require_onceFatal error, the script stopsNo, later calls are skipped

Here is the difference in practice, with a file sidebar.php that does not exist:

PHP
<?php
include __DIR__ . '/partials/sidebar.php';
echo "After include\n";
require __DIR__ . '/partials/sidebar.php';
echo "After require\n";
Output
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
<?php
// config/app.php
return [
    'site_name' => 'Jaipur Sweets',
    'phone' => '+91 98765 43210',
    'gst_rate' => 0.05,
];
PHP
<?php
declare(strict_types=1);

$config = require __DIR__ . '/config/app.php';

echo $config['site_name'] . "\n";
echo 'GST: ' . ($config['gst_rate'] * 100) . "%\n";
Output
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.

PHP
<!-- 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>
PHP
<!-- partials/footer.php -->
<footer>Call us: <?= htmlspecialchars($config['phone']) ?></footer>
</body>
</html>

Each page sets its own variables and then loads the parts:

PHP
<?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:

Output
<!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 include for files the page cannot work without. Use require so a missing file stops the script clearly.
  • Loading a function file twice with require. Use require_once for files that define functions or classes.
  • Output in a config or helper file. A stray blank line after ?> sends output before header() or session_start(). Leave out the closing ?> in files that contain only PHP.

Key points

  • include and require run another file at that spot, sharing the current variables.
  • A missing file gives a warning with include and a fatal error with require.
  • The _once versions 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 return a 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
<?php
// config/app.php
return [
    'site_name' => 'Rohtak Book Store',
    'menu' => ['Home' => 'index.php', 'Contact' => 'contact.php'],
];
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
<?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?

2. Which statement should you use to load a file that defines functions?

3. What does $config = require __DIR__ . '/config/app.php'; store in $config?

4. Why write __DIR__ . '/helpers.php' instead of 'helpers.php'?

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