Himanshu SharmaSoftware engineer
Let’s talk

PHP · Lesson 22 of 54

include, require and splitting code into files

Split PHP code into several files with include, require, include_once and require_once, build paths safely with __DIR__, and share a header and footer.

11 minFunctionsUpdated 22 October 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonOrganise a project into several files and load them reliably with require_once and __DIR__.

Why split code into files

A real project quickly outgrows a single file. You want the database settings in one place, your helper functions in another, and the same page header on every page. PHP can include one file inside another: the included file's code runs at that point, as if it had been typed there.

require and include

Here is a small helper file, functions.php, with one function in it:

php
<?php
function formatPrice(float $amount): string
{
    return "₹" . number_format($amount, 2);
}

Another file, index.php, loads it with require and uses the function:

php
<?php
require __DIR__ . '/functions.php';

echo formatPrice(1499) . "\n";
echo formatPrice(89.5) . "\n";
result
₹1,499.00
₹89.50

include does the same job. The difference is what happens when the file cannot be found:

  • include prints a warning and the script continues without it.
  • require stops the script with a fatal error.
php
<?php
include __DIR__ . '/missing.php';
echo "The script carried on after include\n";
result
Warning: include(/path/to/missing.php): Failed to open stream: No such file or directory in /path/to/index.php on line 2

Warning: include(): Failed opening '/path/to/missing.php' for inclusion (include_path='.:/usr/share/php') in /path/to/index.php on line 2
The script carried on after include

For code your script needs, such as functions, classes and configuration, use require: carrying on without them would only produce stranger errors later. include suits optional pieces, such as a sidebar that may not exist on every site.

require_once and include_once

Including the same file of functions twice is a fatal error, because a function cannot be declared twice. That happens easily when several files each require the same helpers:

php
<?php
require __DIR__ . '/functions.php';
require __DIR__ . '/functions.php';
result
Fatal error: Cannot redeclare formatPrice() (previously declared in /path/to/functions.php:2) in /path/to/functions.php on line 4

The _once versions remember which files are already loaded and skip them the second time:

php
<?php
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/functions.php';   // skipped, already loaded

echo formatPrice(12) . "\n";
result
₹12.00

Use require_once for files that define functions or classes. In modern projects autoloading loads class files for you automatically; Namespaces, autoloading and Composer explains it.

Paths and DIR

A path such as require 'functions.php'; is relative, and PHP resolves it against the include_path setting and the current working directory: the folder the script was started from, which is not always the folder the file is in. A script that works when you open it directly can break when it is included from elsewhere, or run by a scheduled job from another folder.

The magic constant __DIR__ always holds the folder of the file it is written in, so __DIR__ . '/functions.php' is an absolute path that works everywhere. Use it for every include:

php
<?php
require __DIR__ . '/../config/database.php';   // one folder up, then into config/
require __DIR__ . '/partials/header.php';

Configuration files that return values

An included file can end with return, and the require expression then has that value. This is a tidy way to keep settings in their own file:

php
<?php
return [
    'shopName' => "Himanshu's Shop",
    'currency' => 'INR',
    'freeShippingFrom' => 500,
];
php
<?php
$config = require __DIR__ . '/config.php';

echo $config['shopName'] . "\n";
echo "Free shipping from {$config['freeShippingFrom']} {$config['currency']}\n";
result
Himanshu's Shop
Free shipping from 500 INR

Many frameworks, including Laravel, store their configuration exactly like this.

The most common use on websites is a header and footer shared by every page. The included files can contain HTML, and they see the variables of the file that includes them:

php
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title><?= htmlspecialchars($title) ?></title></head>
<body>
<header><a href="/">Himanshu's Shop</a></header>
php
<footer>&copy; <?= date('Y') ?> Himanshu's Shop</footer>
</body>
</html>
php
<?php
$title = "Contact us";
require __DIR__ . '/header.php';
?>
<main><h1>Contact us</h1><p>Email us any time.</p></main>
<?php require __DIR__ . '/footer.php'; ?>
http
GET /contact.php
result
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Contact us</title></head>
<body>
<header><a href="/">Himanshu's Shop</a></header>
<main><h1>Contact us</h1><p>Email us any time.</p></main>
<footer>&copy; 2026 Himanshu's Shop</footer>
</body>
</html>

Change the header once and every page changes. <?= and htmlspecialchars() are explained in Mixing PHP and HTML.

Keep included files out of reach

Files such as config.php are meant to be included, not opened directly in a browser. On a real server, keep them outside the web root (the public folder), so no visitor can request them. That is how this site's Laravel admin is organised: only public_html/ is reachable from the web.

Common mistakes

  • Relative paths without DIR, which break when the working directory changes.
  • Using include for essential files, so the script continues half-loaded.
  • Requiring a function file twice with require instead of require_once.
  • Putting configuration with passwords inside the web root.

Exercise

Create tax.php that defines addGst(float $amount): float (18%), and invoice.php that requires it safely and prints the GST-inclusive price of 2,500 and 999.

Show one possible answer
php
<?php
function addGst(float $amount): float
{
    return round($amount * 1.18, 2);
}
php
<?php
require_once __DIR__ . '/tax.php';

echo addGst(2500) . "\n";
echo addGst(999) . "\n";
result
2950
1178.82

Key points

  • include and require insert and run another PHP file at that point.
  • If the file is missing, include warns and continues; require stops with a fatal error.
  • require_once and include_once skip a file that was already loaded, which avoids redefining functions.
  • Build paths with __DIR__ so they work no matter which folder the script was started from.

Check yourself

1. What is the difference between include and require when the file is missing?
2. Why use require_once for a file of functions?
3. Why is require __DIR__ . '/config.php' safer than require 'config.php'?
4. Can an included file return a value?