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).

// 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).

// 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.

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