Include vs Require

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 124 of 255

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 Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays 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 array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting 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 PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types 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 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 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 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 AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
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.