PHP include and require

Split a site into reusable files with include, require and their _once versions, and build a simple page layout.

Lesson 9 of 86Intermediate17 min read

Most websites repeat the same pieces on every page: the header with the logo and menu, the footer with the copyright line, and often the same helper functions. Copying that HTML into every page means that changing one menu link requires editing every single file, and sooner or later one of them gets missed.

PHP solves this with include and require. They insert the contents of another PHP file at that point, as if you'd typed it there. Write the header once in header.php, include it at the top of every page, and a change to the menu updates the whole site instantly.

In this lesson you'll split a page into reusable parts, learn the difference between include and require, avoid loading the same file twice with _once, build reliable file paths with __DIR__, and organise a small project in a way that scales as it grows.

include and require

PHP
<?php require 'header.php'; ?>
<main>
  <h1>Welcome</h1>
</main>
<?php require 'footer.php'; ?>

Both statements read another file and run it in place, sharing the same variables. The difference is what happens when the file is missing:

StatementIf the file can't be found
include 'file.php';A warning; the rest of the page still runs
require 'file.php';A fatal error; the script stops

Use require for files the page can't work without, such as configuration and functions. include suits optional parts, such as an advert or a sidebar that can safely be missing.

include_once and require_once

If a file defines functions or classes, loading it twice causes an error: "Cannot redeclare function". require_once and include_once remember which files have already been loaded and skip them the second time:

PHP
require_once 'functions.php';
require_once 'functions.php';   // skipped, no error

Use require_once for files of functions, classes and settings. For header and footer templates that should appear exactly where you put them, plain require is fine.

Reliable paths with __DIR__

A relative path such as 'header.php' is looked up from the current working directory, which isn't always the folder of the file doing the including. Pages inside sub-folders can then fail to find their includes.

The magic constant __DIR__ holds the full path of the folder containing the current file, so paths built from it always work:

PHP
require __DIR__ . '/includes/header.php';
require __DIR__ . '/../config.php';      // one folder up

Building every include path from __DIR__ is a small habit that prevents a lot of "failed to open stream" errors when a project grows.

Passing data to templates

Included files share the variables of the file that includes them. Set a variable before including a template, and the template can use it:

PHP
$pageTitle = "Contact us";
require __DIR__ . '/includes/header.php';
PHP
<!-- includes/header.php -->
<title><?= htmlspecialchars($pageTitle ?? 'My site') ?></title>

The ?? operator provides a default when a page forgets to set the variable, and htmlspecialchars() keeps any special characters safe. This simple pattern is the starting point of the templating systems used by frameworks like Laravel.

PHP include and require Syntax

include and require

require 'file.php';
include 'optional.php';
require_once __DIR__ . '/includes/functions.php';
include_once __DIR__ . '/sidebar.php';

PHP include and require Summary

  • include and require insert another PHP file at that point, sharing its variables.
  • A missing include gives a warning; a missing require stops the script.
  • require_once and include_once load a file only once, preventing redeclare errors.
  • Build paths with __DIR__ so includes work from any folder.
  • Set variables before including a template to pass data to it.

PHP include and require Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A shared header and footer

PHP
<?php
// includes/header.php
?>
<!DOCTYPE html>
<html>
<head><title><?= htmlspecialchars($pageTitle ?? 'Bakery') ?></title></head>
<body>
<nav><a href="index.php">Home</a> | <a href="menu.php">Menu</a></nav>
PHP
<?php
// menu.php
$pageTitle = 'Our menu';
require __DIR__ . '/includes/header.php';
?>
<h1>Today's menu</h1>
<p>Cinnamon buns, sourdough and lemon cake.</p>
<?php require __DIR__ . '/includes/footer.php'; ?>
Output
<!DOCTYPE html>
<html>
<head><title>Our menu</title></head>
<body>
<nav><a href="index.php">Home</a> | <a href="menu.php">Menu</a></nav>
<h1>Today's menu</h1>
<p>Cinnamon buns, sourdough and lemon cake.</p>
<footer>© 2024 Bakery</footer>
</body>
</html>
Line-by-line explanation
  1. Line 5In header.php, the title uses the variable set by the page, or "Bakery" if none was set.
  2. Lines 3 to 4In menu.php, set the title, then pull in the shared header.
  3. Line 8In menu.php, the footer file adds the closing footer, body and html tags.
Example 2

A functions file loaded once

PHP
<?php
// includes/functions.php
function formatPrice(float $amount): string {
    return '£' . number_format($amount, 2);
}
PHP
<?php
// shop.php
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/functions.php';

echo formatPrice(3.5), "\n";
echo formatPrice(24.499), "\n";
Output
£3.50
£24.50
Line-by-line explanation
  1. Lines 3 to 4In shop.php, the second require_once is skipped, so formatPrice isn't declared twice.
  2. Lines 6 to 7number_format rounds to two decimal places.
Example 3

include versus require when a file is missing

PHP
<?php
include 'missing-banner.php';
echo "Page continues after include\n";

require 'missing-config.php';
echo "This line never runs\n";
Output
Warning: include(missing-banner.php): Failed to open stream: No such file or directory
Page continues after include
Fatal error: Uncaught Error: Failed opening required 'missing-config.php'
Line-by-line explanation
  1. Lines 2 to 3include only warns, so the page carries on.
  2. Lines 5 to 6require stops the script with a fatal error.

Common PHP include and require Mistakes

Including a functions file twice

Don't
require 'functions.php';
require 'helpers.php';      // which also requires functions.php
// Fatal error: Cannot redeclare formatPrice()
Do
require_once 'functions.php';
require_once 'helpers.php';

Relative paths from a sub-folder

Don't
// admin/users.php
require 'includes/header.php';           // looks in the wrong place
Do
// admin/users.php
require __DIR__ . '/../includes/header.php';

Including files chosen by the user

Don't
include $_GET['page'] . '.php';      // a visitor can choose any file
Do
$pages = ['home', 'about', 'contact'];
$page = in_array($_GET['page'] ?? '', $pages) ? $_GET['page'] : 'home';
include __DIR__ . "/pages/$page.php";

Never build include paths from raw user input; check it against a list of allowed values.

PHP include and require in Real Projects

Includes in real PHP sites

WordPress themes are built from includes: header.php, footer.php and sidebar.php are loaded into every page with functions such as get_header(). Frameworks use Composer's autoloader, which is a smarter require_once, so classes are loaded automatically the moment you use them. Small hand-built sites follow the exact pattern you practised here.

PHP include and require FAQ

Can an included file return a value?

Yes. A file can end with return [...];, and $config = require 'config.php'; stores that value. This is a common pattern for configuration files, because the settings are kept in one place and loaded into a variable instead of creating globals.

Are include and require functions?

They're language constructs, so the brackets are optional: require 'header.php'; and require('header.php'); both work. The usual style is without brackets. Because they aren't functions, they can't be passed as callbacks.

Is require_once slower than require?

Very slightly, because PHP checks whether the file was already loaded. With OPcache enabled, as on any modern server, the difference is negligible. Choose based on behaviour: require_once for definitions, require for templates that may intentionally appear more than once.

Can I include a file from another website?

Don't. Including remote URLs requires the allow_url_include setting, which is off by default because it would run code from another server on yours. Download data with an HTTP client and treat it as data, never as code to include.

Where should configuration files with passwords live?

Outside the public web folder, so a browser can never request them directly, and out of version control. Load them with require __DIR__ . '/../config.php'; or read secrets from environment variables, as the environment configuration lesson shows.

PHP include and require Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the line so the page stops if the config file is missing.

 __DIR__ . '/config.php';
Multiple choiceeasy

What happens when an included file doesn't exist?

Multiple choicemedium

Which statement prevents "Cannot redeclare function" errors?

Predict the outputmedium

main.php sets $name = "Ana"; and then includes greet.php, which contains <?php echo "Hi $name";. What is output?

Multiple choicehard

What does __DIR__ contain?

PHP include and require Quiz

5 questions to check what you learned.

  1. Why put the site header in its own file?

    • It makes pages load faster
    • So it's written once and changes update every page
    • PHP requires it
    • To hide it from visitors
  2. When should you use require instead of include?

    • For optional parts like adverts
    • Never
    • For files the page can't work without, such as config and functions
    • Only for HTML files
  3. Do included files have access to variables defined before the include?

    • No
    • Yes
    • Only global constants
    • Only if declared public
  4. What does $pageTitle ?? 'My site' do in a template?

    • Always prints My site
    • Compares the two strings
    • Throws an error if $pageTitle is missing
    • Uses $pageTitle if it's set, otherwise 'My site'
  5. Why is include $_GET['page'] dangerous?

    • Visitors could make the site load files it shouldn't
    • It's slow
    • $_GET doesn't work with include
    • It only works on Linux