Include vs Require

Su Subhalakshmi Chandran Updated 05 Nov 2026
6 min read ·Lesson 242 of 248

PHP has four statements for loading another file: include, require, include_once, and require_once. They all insert and run the file in the same way (see PHP Include). The differences are what happens when the file cannot be loaded and whether a file may be loaded more than once. Choosing the right one makes failures obvious and prevents duplicate-definition errors.


The Four Statements at a Glance

StatementFile Missing or UnreadableFile Already Loaded
includeWarning; script continues; returns falseLoaded again
requireFatal error; script stopsLoaded again
include_onceWarning; script continuesSkipped (returns true)
require_onceFatal error; script stopsSkipped (returns true)

In other words:

  • require = "this file is essential; stop if it is missing."
  • include = "this file is optional; continue without it."
  • _once = "load this file at most once per request."

include: Continue on Failure

<?php
echo "Start\n";

include __DIR__ . '/optional-banner.php';   // file does not exist

echo "End\n";

Output

Start
PHP Warning:  include(/path/optional-banner.php): Failed to open stream: No such file or directory in /path/index.php on line 4
PHP Warning:  include(): Failed opening '/path/optional-banner.php' for inclusion (include_path='.:/usr/share/php') in /path/index.php on line 4
End

The warnings are logged (and displayed, if display_errors is on), but the script continues to End.

When include Is Appropriate

  • An optional part of a page, such as a promotional banner that may not exist.
  • An optional configuration file that overrides defaults, checked with is_file() first:
<?php
$config = require __DIR__ . '/config/app.php';

$localFile = __DIR__ . '/config/local.php';
if (is_file($localFile)) {
    $config = array_replace($config, include $localFile);
}

Checking with is_file() before including avoids the warnings entirely when the absence of the file is expected.


require: Stop on Failure

<?php
echo "Start\n";

require __DIR__ . '/config/database.php';   // file does not exist

echo "End\n";

Output

Start
PHP Warning:  require(/path/config/database.php): Failed to open stream: No such file or directory in /path/index.php on line 4
PHP Fatal error:  ... Failed opening required '/path/config/database.php' (include_path='.:/usr/share/php') in /path/index.php on line 4

End is never printed. The script stops immediately at the missing file. (The exact wording of the fatal error line varies slightly between PHP versions.)

Why Stopping Is Better for Essential Files

If the database configuration is missing, the application cannot work correctly. With include, it would continue and fail later — for example, with "Undefined variable $pdo" or an error deep inside a database call — making the real cause hard to find. With require, the error points directly at the missing file.

Use require (or require_once) for:

  • Bootstrap files and configuration
  • Function and class definition files
  • Composer's vendor/autoload.php
  • Layout templates that every page needs

The _once Variants

The Problem They Solve

Files that define functions, classes, or constants can be loaded only once. A second load tries to define them again:

<?php
// helpers.php defines function formatPrice()
require __DIR__ . '/helpers.php';
require __DIR__ . '/helpers.php';

Result

PHP Fatal error:  Cannot redeclare function formatPrice() (previously declared in /path/helpers.php:2) in /path/helpers.php on line 2

This often happens indirectly: orders.php requires helpers.php, invoices.php also requires helpers.php, and a page requires both orders.php and invoices.php.

The Solution

<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/helpers.php';   // skipped

echo formatPrice(250) . "\n";

Output

₹250.00

PHP remembers which files were loaded (by their resolved full path) and skips any later _once request for the same file.

When Not to Use _once

Templates that should output content each time they are included — such as a product card rendered in a loop — must use plain include or require:

<?php
$products = [['name' => 'Pen'], ['name' => 'Notebook']];

foreach ($products as $product) {
    include __DIR__ . '/templates/product-row.php';   // runs for every product
}

With include_once, only the first product would be displayed.


Choosing the Right Statement

File TypeRecommendedReason
Composer autoloader (vendor/autoload.php)require_once / requireEssential; must load once
Configuration returning an arrayrequireEssential; can be loaded where needed
Function or constant definitionsrequire_onceEssential; must not be redefined
Layout parts (header, footer)requireEssential for the page
Repeated templates (rows, cards)include / requireMust run every time
Optional filesis_file() check + includeAbsence is acceptable

A simple rule of thumb: use require by default, add _once for files that define things, and use include only when a missing file is genuinely acceptable.


Return Values

All four statements are expressions with a return value:

SituationValue
The file executes return $value;$value
The file has no return1
include / include_once failsfalse (with warnings)
_once skips an already loaded filetrue
<?php
$first = require_once __DIR__ . '/config/app.php';   // returns the array
$second = require_once __DIR__ . '/config/app.php';  // already loaded

var_dump(is_array($first));
var_dump($second);

Output

bool(true)
bool(true)

This is why configuration files that return values should be loaded with require, not require_once: a second require_once returns true instead of the configuration array, which leads to confusing bugs when two parts of the application load the same configuration.


Paths and include_path

All four statements resolve paths in the same way:

Path FormHow It Is Resolved
Absolute (/var/www/app/config.php, or built with __DIR__)Used as given
Starting with ./ or ../Relative to the current working directory
Plain relative (config.php)Searched in the include_path setting, then the calling script's directory

Because the current working directory changes depending on how a script is started (web server, cron job, command line), the reliable approach is always:

require __DIR__ . '/relative/path/to/file.php';

Performance

  • The _once variants must check whether a file was already loaded. With OPcache enabled (standard in production), this check and the file loading itself are very fast; there is no practical reason to avoid _once for definition files.
  • OPcache stores compiled files in memory, so including many small files has little overhead in production.
  • Loading files that are not needed for a request still costs time. Autoloading (loading a class file only when the class is first used) avoids this for classes.

Common Mistakes

Using include for Essential Files

Effect: The script continues in a broken state and fails later with misleading errors.

Fix: Use require for anything the application needs.

Using require_once for Configuration Arrays

Effect: The second load returns true instead of the array.

Fix: Use require for files that return values, or load the configuration once and pass it around.

Using _once for Repeated Templates

Effect: The template renders only the first time.

Fix: Use include or require for templates that must run multiple times.

Suppressing Errors With @include

Effect: Real problems (typos in paths, permission errors) are hidden.

Fix: Check is_file() first when a file is optional.

Relative Paths

Effect: Files are found when running in the browser but not from cron or the command line.

Fix: Build paths with __DIR__.


Best Practices

  • Use require by default, require_once for definition files, and include only for truly optional files.
  • Use require (not _once) for configuration files that return arrays.
  • Always build include paths from __DIR__.
  • Let Composer's autoloader load classes; keep manual includes for bootstrap, configuration, and templates.
  • Enable OPcache in production.

Official reference: https://www.php.net/manual/en/function.require.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files
Ask about this post
AI Ask about this post

Ask questions about Include vs Require and get answers drawn from it.

Signed-in readers only.