๐Ÿ“ Web Development

PHP include and require: Reuse Code Across Pages

Sep 4, 20265 min read2 viewsBy Flow

PHP include is how one file borrows the contents of another. Every site has a header, a navigation bar and a footer that look the same on every page, and copying that markup into twenty files means changing it in twenty places later. This lesson covers include and require, the two keywords that fix that, and the small differences between them that decide which one you should reach for.

The problem it solves

PHP include exists for exactly this problem. So far every script in this series has been one file that does one thing. A real site is not like that. The moment you have an About page and a Contact page, both need the same header, and the day you add a menu item you do not want to edit both.

Put the shared markup in its own file and pull it in where you need it. Two files here โ€” header.php and footer.php โ€” hold the parts that repeat:

<!-- header.php -->
<h1>Flow's Demo Site</h1>
<p><a href="#">Home</a> | <a href="#">About</a> | <a href="#">Contact</a></p>
<hr>

And the page itself only holds what is actually unique to it:

<?php
include "header.php";
?>

<h2>About this page</h2>
<p>This part is unique to the About page.</p>

<?php
include "footer.php";
?>

Output

PHP include output showing a header and footer file combined into one page

Three files, one page. A PHP include takes the contents of the named file and drops them in at exactly the point the statement appears, as if you had typed them there yourself. Change the menu in header.php and every page that includes it changes with it.

include or require โ€” the difference that matters

PHP gives you two keywords that do the same job, and the choice between them is the first real decision a PHP include asks of you. The only difference is what happens when the file is missing, and that difference is bigger than it sounds:

<?php
echo "Line 1: before the include.<br>";

include "does-not-exist.php";

echo "Line 2: include kept going.<br>";

require "does-not-exist.php";

echo "Line 3: you will never see this.";
?>

Output

PHP include warning versus require fatal error output in the browser

include emits a warning and carries on to line 2. require emits a fatal error and stops the script dead โ€” line 3 never runs.

That gives you a simple rule. If the page is broken without the file, use require. A database connection, a config file, a function library your page cannot work without โ€” those are all require. If the file is a nice-to-have and the page still makes sense without it, include is fine. A sidebar advert is a reasonable include.

Most of the time you want require. A half-rendered page that carries on after losing its database connection is worse than an honest error.

The double-include problem

Here is the PHP include trap that catches everyone once. This file defines a function:

<?php
// greet.php
function greet($name) {
    return "Hello, " . $name . "!";
}
?>

Include it twice โ€” which is easy to do by accident once one included file includes another โ€” and PHP objects:

<?php
include "greet.php";
include "greet.php";

echo greet("Umair");
?>

Output

PHP include error output showing cannot redeclare function greet

A function can only be declared once. The second include tries to declare greet() again and the script dies. The fix is a different keyword:

<?php
include_once "greet.php";
include_once "greet.php";

echo greet("Umair");
?>

Output

PHP include_once output showing the same file included twice without an error

include_once keeps a record of what it has already pulled in and quietly skips the repeat. require_once does the same with require's fatal behaviour. So there are four keywords in total:

KeywordMissing fileIncluded twice
includeWarning, script continuesRuns again
requireFatal error, script stopsRuns again
include_onceWarning, script continuesSkipped
require_onceFatal error, script stopsSkipped

For anything that declares functions or classes, use the _once version. For a header or footer that is meant to appear where you put it, plain include is correct โ€” you may genuinely want it twice.

Variables cross the boundary

A PHP include is not a sealed box. It runs inside the scope of the line that included it, so variables flow both ways:

<?php
$username = "Umair";

include "show-user.php";

echo "Back in the main file, \$role is: " . $role;
?>

Where show-user.php reads the variable it was handed and sets a new one:

<?php
echo "Inside the included file, \$username is: " . $username . "<br>";

$role = "editor";
?>

Output

PHP include output showing variable scope shared between the two files

This is genuinely useful โ€” it is how you pass a page title into a shared header. It is also how you create confusing bugs, because an included file can overwrite a variable you were still using. Keep included files small and be deliberate about what they touch.

An include can return a value

A less-known trick, and the tidiest way to handle configuration. If the included file uses return, the include statement evaluates to that value:

<?php
// config.php
return [
    "site_name" => "Flow's Demo Site",
    "per_page"  => 10,
    "debug"     => false,
];
<?php
$config = include "config.php";

echo "Site name: " . $config["site_name"] . "<br>";
echo "Posts per page: " . $config["per_page"] . "<br>";
echo "Debug mode: " . ($config["debug"] ? "on" : "off");
?>

Output

PHP include output showing a config array returned from an included file

Nothing leaks into the global scope โ€” you get one array in one variable of your choosing. Most modern PHP projects, framework or not, keep their settings exactly this way.

Paths are relative to the running script

This is the part of PHP include behaviour that breaks in production. include "header.php" looks for the file relative to the script the browser actually requested, not relative to the file the include is written in.

Move a page into a subfolder and the relative path silently points somewhere else. The fix is __DIR__, a magic constant holding the folder of the current file:

<?php
// Fragile โ€” depends on which script is running
include "../header.php";

// Reliable โ€” always relative to THIS file
include __DIR__ . "/../header.php";
?>

Output

PHP include output using __DIR__ to include a file from a parent folder

Get into the habit early. __DIR__ costs you nine characters and removes an entire category of bug that only shows up after you reorganise your folders.

Three mistakes with PHP include

Using include where the page cannot survive without the file. A missing database config with include gives you a warning and then a wall of undefined-variable errors. With require you get one clear message. Fail loudly.

Reaching for _once everywhere. It is not a free upgrade โ€” PHP has to track what it has loaded, and more importantly it hides genuine double-include bugs instead of showing them to you. Use it for declarations, not for markup.

Building an include path from user input. include $_GET["page"] . ".php" looks convenient and is one of the oldest holes in PHP. It lets a visitor request files you never meant to expose. Match the input against a fixed list of allowed pages and include only from that list.

Common questions about PHP include

The questions that come up most once a project grows past a single file.

What is the difference between include and require in PHP?

Only the failure behaviour. Both perform the same PHP include of the file's contents. If the file is missing, include gives a warning and the script continues; require gives a fatal error and the script stops. When the file loads successfully they are identical. Use require whenever the page is meaningless without the file.

Should I use include or include_once?

Use include_once for files that declare functions or classes, because declaring the same function twice is a fatal error. Use plain include for markup like a header or a repeated card, where including it more than once may be exactly what you want.

Can an included file see the variables from the file that included it?

Yes. The included file runs in the same scope as the include statement, so it can read variables that already exist and any variable it creates is available afterwards in the including file too. That is how you pass a page title into a shared header.

Why does my include work locally but break on the server?

Almost always a path problem. Relative paths resolve against the script the browser requested, and case matters on Linux servers even though it does not on Windows. Use __DIR__ . "/file.php" and match the file's capitalisation exactly.

Does include slow down a PHP page?

Not in any way you will notice. Each PHP include is a file read, and PHP's opcode cache keeps compiled files in memory on a real server. Splitting a site into sensible files is worth far more than the microseconds it costs.

What is next

You can now split a site into files and pull them back together, which is the point where a collection of scripts starts behaving like an actual website. The next thing most beginners want is to accept something from a visitor โ€” and the safest place to start is a form.

Head to PHP forms if you have not already, and then PHP sessions to remember who that visitor is between pages.

Comments

Loading comments...

Link copied to clipboard