PHP Include Files
The include and require statements let you pull the contents of one PHP file into another, so you can reuse headers, footers, menus, and configuration across many pages.
Why include files?
As a website grows, the same pieces of code appear on page after page: a navigation bar, a footer, a database connection, a list of helper functions. Copying that code into every file is hard to maintain, because a single change means editing dozens of pages. PHP solves this with include and require, which insert the code from another file at the point where the statement appears.
When PHP reaches an include statement, it reads the named file, runs any PHP inside it, and treats the rest as output, exactly as if you had typed that content directly into the current file. Variables and functions defined in the included file become available to the code that follows.
Sharing a header and footer
<?php
// header.php
echo "<header><h1>My Website</h1></header>";
?>
<?php
// index.php
include "header.php";
echo "<main>Welcome to the home page.</main>";
include "footer.php";
?>include vs. require
Both statements do the same job, but they behave differently when the target file cannot be found. include emits a warning and lets the script keep running, while require raises a fatal error and stops execution completely. Choose based on how essential the file is to the page.
The _once variants
include_once and require_once behave like their counterparts but remember which files have already been pulled in. If the same file is requested a second time, they skip it. This prevents errors from redefining a function or class, which is why _once is the safe default when loading files that declare functions or classes.
Loading config and helpers safely
<?php
// config.php defines database settings used everywhere
require_once "config.php";
// functions.php declares reusable functions
require_once "functions.php";
// Calling it twice is harmless: the second call is ignored
require_once "functions.php";
echo greetUser("Ada");
?>- Included files share the scope of the line where they are included, so variables carry over both ways.
- Prefer require_once for configuration, function libraries, and class definitions.
- Paths are resolved relative to the including file or the include_path setting; using __DIR__ makes paths reliable.
- Keep included files free of stray whitespace before <?php to avoid accidental output before headers are sent.
Exercise: PHP Include
What happens when include or require target a missing file?