Difference Between Include and Require in PHP
In PHP development, importing external files is a fundamental task,
primarily achieved using the include and
require statements. While both serve the purpose of
inserting the content of one PHP file into another, they handle errors
differently when the specified file cannot be found. This article
explains the core differences between include and
require, how they impact application flow, and when to use
each to ensure your website functions correctly.
The Core Difference: Error Handling
The fundamental distinction between include and
require lies in how the PHP engine reacts when the target
file is missing or contains a path error.
1. The include
Statement
When you use include and the file is not found, PHP
generates a Warning (E_WARNING).
- Behavior: The script will issue a warning message,
but it will not stop executing. The PHP engine will continue to parse
and run the remaining code after the
includestatement. - Use Case: Use
includefor non-critical files, such as a website footer, sidebar, or HTML templates. If the footer fails to load, the user can still read the main content of the page.
// If footer.php is missing, the script still prints "Hello World!"
include 'footer.php';
echo "Hello World!";2. The require
Statement
When you use require and the file is not found, PHP
generates a Fatal Error
(E_COMPILE_ERROR).
- Behavior: The script will stop executing
immediately. No further code below the
requirestatement will be processed. - Use Case: Use
requirefor files that are critical to the application’s functionality, security, or data integrity. Examples include database configuration files, security helper functions, or class libraries. If these files are missing, running the rest of the script could cause severe security vulnerabilities or broken functionality.
// If database.php is missing, the script stops immediately and "Hello World!" is never printed
require 'database.php';
echo "Hello World!";What About
include_once and require_once?
PHP also provides variations of these statements:
include_once and require_once.
include_once: Behave exactly likeinclude, but PHP will check if the file has already been included. If it has, it will not include it again.require_once: Behaves exactly likerequire, but PHP will check if the file has already been imported. If it has, it will ignore the second request.
These variations are highly useful for importing file dependencies, like helper functions or classes, where redefining them multiple times would cause a “redeclaration error.”
Quick Comparison Summary
| Feature | include |
require |
|---|---|---|
| Error Level | Warning (E_WARNING) |
Fatal Error
(E_COMPILE_ERROR) |
| Script Execution | Continues running | Stops immediately |
| Best Used For | Non-essential layout elements (headers, footers, sidebars) | Critical application components (DB configs, functions, classes) |
| Once-Only Alternative | include_once |
require_once |