PHP File Inclusion

Real websites repeat many parts on every page, like the header, the menu and the footer. Instead of copying the same code in every file, you write it once in a separate file and include it wherever you need. If you change that file, all pages are updated.


include and require

PHP gives four statements for this job.

StatementIf the file is missingIncludes again?
includeWarning, script continuesYes
requireFatal error, script stopsYes
include_onceWarning, script continuesNo, only one time
require_onceFatal error, script stopsNo, only one time

The difference is explained in include() vs require(). Use require_once for files that your page must have (like the database connection), and include for optional parts.


Example: header and footer

First create the files header.php and footer.php.

<?php
// header.php
echo "<header><h2>My Website</h2></header>";
?>
<?php
// footer.php
echo "<footer>Copyright " . date("Y") . "</footer>";
?>

Now include them in a page.

<?php
include "header.php";

echo "<p>Welcome to my home page.</p>";

include "footer.php";
?>

Output:

Tutorials Class - Output Window

My Website
Welcome to my home page.
Copyright 2026


Use the correct file path

A relative path like "header.php" depends on where the script runs from, and it can break when you include a file from another folder. The safe way is to build the path from __DIR__, the folder of the current file.

<?php
require_once __DIR__ . "/includes/db-connection.php";
?>

Get a value from an included file

An included file can return a value. This is often used for settings.

<?php
// config.php
return [
    "site_name" => "Tutorials Class",
    "per_page" => 10
];
?>
<?php
$config = require __DIR__ . "/config.php";

echo $config["site_name"];
?>

Output:

Tutorials Class - Output Window

Tutorials Class


Security

  • Never include a file whose name comes from the visitor, like include $_GET["page"]. An attacker can include any file of your server (this is called local file inclusion).
  • If you need dynamic pages, compare the name with a fixed list of allowed files.
  • Keep important files like config outside the public folder. See PHP Security Tips.

Next chapter: PHP Session.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is include() function in PHP?
Can we include a file two times in any PHP page?
Which is the PHP function to delete a file from server?
What is fopen function PHP?
What is the difference between unlink() and unset() in PHP?
How to check if a file exists in PHP?
How to get the size of a file in PHP?