Include vs Require in PHP: Key Differences and Usage Guide
include and require both insert code from one file into another, but require causes a fatal error and stops the script if the file is missing, while include only gives a warning and continues running. Use require when the file is essential, and include when the file is optional.Quick Comparison
This table summarizes the main differences between include and require in PHP.
| Factor | include | require |
|---|---|---|
| Error on missing file | Warning (non-fatal) | Fatal error (stops script) |
| Script continuation after error | Yes, continues | No, stops immediately |
| Use case | Optional files | Essential files |
| Behavior on multiple includes | Includes every time | Includes every time |
| Common usage | Templates, optional configs | Core libraries, critical configs |
Key Differences
The main difference between include and require lies in how PHP handles errors when the specified file is missing or unreadable. include generates a warning but allows the script to continue running, which means your program can still execute other code even if the included file is not found.
On the other hand, require triggers a fatal error if the file cannot be loaded, immediately stopping the script. This behavior ensures that critical files, such as configuration or essential functions, must be present for the program to run.
Both statements insert the content of the specified file at the point where they are called, but choosing between them depends on whether the file is optional or mandatory for your application.
Include Example
This example shows how include works when including a file that exists and what happens if the file is missing.
<?php // file: greeting.php function greet() { echo "Hello from included file!\n"; } // main.php include 'greeting.php'; greet(); include 'missing.php'; echo "This line still runs despite missing file.\n"; ?>
Require Equivalent
This example shows how require behaves with the same files. Notice the script stops on missing file.
<?php // file: greeting.php function greet() { echo "Hello from required file!\n"; } // main.php require 'greeting.php'; greet(); require 'missing.php'; echo "This line will NOT run because require stops script.\n"; ?>
When to Use Which
Choose require when the file is essential for your program to run, such as configuration files, database connections, or core functions. This ensures your script stops immediately if something critical is missing, preventing unexpected behavior.
Use include when the file is optional, like templates, optional features, or user content. This way, your script can continue running even if the file is not found, allowing graceful degradation.
Key Takeaways
require for files your script cannot run without.include for optional files where script continuation is allowed.require stops the script on failure; include only warns and continues.