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.
| Statement | If the file is missing | Includes again? |
|---|---|---|
| include | Warning, script continues | Yes |
| require | Fatal error, script stops | Yes |
| include_once | Warning, script continues | No, only one time |
| require_once | Fatal error, script stops | No, 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:
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
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.
| Exercises & Assignments |
|---|
| No Content Found. |