include vs. require: Key Differences
The two commands serve similar purposes, but they differ significantly in how they handle errors.
- The
includestatement issues a warning and continues script execution when an error occurs. - The
requirestatement, however, stops the script immediately if an error happens.
This article explains the differences between include and require and guides you on how to choose the appropriate command for your needs.
include vs. require Comparison
While both include and require are used in PHP to include one file within another, they have a key difference:
include generates a warning if the included file is missing but allows the script to continue running, whereas require causes a fatal error and stops the script immediately if the file is not found.
| Comparison Aspect | include |
require |
|---|---|---|
| Functionality | Includes a file using the include statement. |
Includes a file using the require statement. |
| Usage Example | include 'filepath.php' |
require 'filepath.php' |
| Error Handling | Issues a warning and continues script execution. | Triggers a fatal error and halts the script immediately. |
| Duplicate Inclusion | Duplicates are allowed. | Duplicates are allowed. |
There are also modified versions of these commands called include_once and require_once.
As their names suggest, these commands check whether the file has already been included, and if so, they prevent including it again. This is useful to avoid errors or unintended behavior caused by redefining functions or variables when including the same file multiple times. However, compared to include and require, they execute slightly slower.
| Comparison Aspect | include_once |
require_once |
|---|---|---|
| Functionality | Includes a file using the include_once statement. |
Includes a file using the require_once statement. |
| Usage Example | include_once 'filepath.php' |
require_once 'filepath.php' |
| Error Handling | Issues a warning and continues script execution. | Triggers a fatal error and halts the script immediately. |
| Duplicate Inclusion | Duplicates are prevented. | Duplicates are prevented. |
How to Choose Between include and require
Both include and require are statements used to incorporate files into your PHP script. Which one to use depends on your specific situation and requirements. Below are guidelines to help you make the right choice.
- Whether the file is mandatory
- Whether the file is optional
- Whether duplicate inclusion is allowed
- Error handling requirements
Whether the File Is Mandatory
If the file you want to include is essential to the script—meaning the script cannot run properly without it—you should use require. If the specified file is missing, require will throw a fatal error and halt the execution of the script. This makes it useful when the included file is critical for correct behavior.
Example scenario — including database connection information in a web application.
// database.php
// Database connection details
$host = 'localhost';
$username = 'myusername';
$password = 'mypassword';
// Other database settings
// Establish database connection
$db = new PDO("mysql:host=$host;dbname=mydatabase", $username, $password);
// main.php
// Database connection info is mandatory
require 'database.php';
// Execute remaining code
// Perform database-related operations
In this example, database.php contains critical database connection details needed by main.php. Without this file, main.php cannot function correctly.
Therefore, the require statement is used to mandatorily include database.php. This means that if the file is missing, a fatal error occurs, and the script halts immediately. This approach ensures the presence of essential files and guarantees the script runs only when required resources are available.
Whether the File Is Optional
If the file you want to include is not critical and does not affect the script’s core functionality, use include. The include statement will issue a warning if the file is missing but will continue running the script. This is useful for files that provide optional features.
Example scenario — including a logging file in a web application.
// logging.php
// Function to write logs
function write_log($message) {
// Logging implementation
// ...
}
// main.php
// Optionally include logging file
include 'logging.php';
// Continue with the rest of the code
// Write logs when needed
write_log('Event occurred');
Here, logging.php contains functions to support logging, which is an optional feature. Including it with include allows the script to run normally even if the logging file is missing, providing flexibility without disrupting core functionality.
Whether Duplicate Inclusion Is Allowed
Choose between include and require based on whether you need to include the same file multiple times. If duplication is required, use include. If you want to prevent duplicate inclusions, use include_once or require_once.
Example scenario — including a module file multiple times on a web page.
// module.php
// Output module content
echo 'This is a module.';
// ...
// main.php
// Duplicate inclusion of a module file
include 'module.php';
include 'module.php';
// Output page content
echo '<main>';
// ...
echo '</main>';
In this case, module.php is a module that might need to be included multiple times. Using include allows multiple inclusions of the same file as needed. If preventing duplication is necessary, switch to include_once or require_once.
Error Handling Requirements
The choice between include and require also depends on how you want your script to handle errors. include will emit a warning on failure but continue executing, whereas require will cause a fatal error and stop execution immediately. Use require when you need to stop the script on error.
Example scenario — including a configuration file in a web application.
// config.php
// Configuration settings
$database_host = 'localhost';
$database_username = 'myusername';
$database_password = 'mypassword';
// ...
// main.php
// Mandatory inclusion of configuration file
require 'config.php';
// Continue with the rest of the code
// Use configuration settings
$connection = new DatabaseConnection($database_host, $database_username, $database_password);
// ...
Here, config.php contains essential configuration data. The script must halt if this file is missing or has errors.
Thus, require is used to ensure mandatory inclusion of config.php. This way, the script fails fast on missing or faulty configuration, safeguarding the application’s stability.
This section outlines how to select the appropriate inclusion statement based on the importance of the file, optionality, duplication needs, and error handling policies. Proper use of include, require, and their _once variants is essential for robust and maintainable PHP applications.
Understanding the Importance of include and require
Understanding the differences between include and require offers several advantages for PHP developers:
- Flexible Code Structure:
Knowing when to use
includeandrequireallows you to modularize your code and break it into reusable components. You can include necessary files at the appropriate time, making your code more adaptable and maintainable. - Handling Required Files:
The
requirestatement is useful for including files that are essential for the application to function. If the file is missing, it triggers a fatal error and stops the script, ensuring that critical dependencies are not silently ignored. - Handling Optional Files:
The
includestatement is ideal for optional files. If the file is not found, a warning is issued, but the script continues to run. This makes it useful for features that enhance functionality but are not required for basic execution. - Preventing Duplicate Inclusions:
You can use
include_onceandrequire_onceto prevent a file from being included multiple times. This helps maintain consistency and avoids redefinition errors. - Controlling Error Behavior:
Since
requirehalts the script when an error occurs, it provides better control over how your application handles missing or broken dependencies. It ensures that critical issues are surfaced immediately.
These benefits help PHP developers create well-structured and flexible code, properly manage required and optional files, and control duplicate inclusion and error handling. By leveraging these tools effectively, you can build more reliable and maintainable PHP applications.
Summary
Understanding the differences between include, require, include_once, and require_once is essential for writing modular, maintainable PHP code. Use require when the file is critical to the application’s functionality, and include when the file is optional. To prevent duplicate inclusions, rely on include_once or require_once. Choosing the right inclusion method improves code clarity, ensures proper error handling, and helps maintain a reliable execution flow.