Question

PHP require vs include vs require_once vs include_once Explained

phpincluderequirerequire-once

Question

In PHP, what is the difference between require, include, require_once, and include_once?

Specifically:

  • When should require be used instead of include?
  • When should require_once be used instead of include_once?
  • How do these choices affect error handling and script execution?

Example:

<?php
require 'config.php';
include 'sidebar.php';
require_once 'database.php';
include_once 'helpers.php';

I want to understand when each statement is appropriate and what happens if the file cannot be loaded or is included multiple times.

Short Answer

By the end of this page, you will understand how PHP loads files with require, include, require_once, and include_once, what happens when a file is missing, and how to choose the right one in real projects. You will also learn why the _once versions help prevent duplicate loading problems such as function redeclaration and repeated setup code.

Concept

PHP often splits code into multiple files:

  • configuration files
  • reusable functions
  • templates and layouts
  • database setup
  • class definitions

To bring one file into another, PHP provides four related statements:

  • require
  • include
  • require_once
  • include_once

The core differences are about importance and duplication.

1. require vs include

Both load and execute another PHP file.

The important difference is what happens when the file cannot be loaded:

  • require causes a fatal error and stops the script
  • include causes a warning and the script usually continues

Use this rule:

  • Use require for files your program must have to work
  • Use include for files that are optional or non-critical

2. require_once vs include_once

The _once versions do the same job, but PHP checks whether the file has already been loaded.

  • If it has not been loaded yet, PHP loads it
  • If it has already been loaded, PHP skips it

This is useful when a file defines:

  • functions
  • classes
  • constants
  • setup code that should run only once

Without _once, loading the same file twice can cause problems such as:

  • Cannot redeclare function ...
  • class redeclaration errors
  • repeated initialization

Why this matters

In real programs, file loading affects:

  • whether your app can safely start
  • whether duplicate code runs by mistake
  • how missing dependencies are handled
  • how modular and maintainable your code is

A missing database connection file should usually stop the app. A missing optional widget file might not need to. That is exactly the kind of decision these statements represent.

Mental Model

Think of your PHP app like preparing a presentation.

  • require means: "I cannot give this presentation without this file."
  • include means: "This file would be helpful, but I can continue without it."
  • require_once means: "I must have this file, but only once."
  • include_once means: "Add this file if possible, but never add it twice."

Another way to think about it:

  • require = mandatory part
  • include = optional part
  • _once = prevent duplicates

So the decision has two layers:

  1. Is the file required or optional?
  2. Should it be loaded only once?
Take Quiz

Syntax and Examples

Core syntax

<?php
require 'file.php';
include 'file.php';
require_once 'file.php';
include_once 'file.php';

Example 1: Required file

<?php
require 'config.php';

echo "Application started";

If config.php is missing, PHP stops execution because the application depends on it.

Example 2: Optional file

<?php
include 'promo-banner.php';

echo "Main page content";

If promo-banner.php is missing, PHP shows a warning, but the rest of the page may still run.

Example 3: Prevent duplicate loading

helpers.php

<?php
function formatPrice($price) {
    return '$' . number_format($price, 2);
}

Main file:

<?php
require_once 'helpers.php';
require_once 'helpers.php';

echo formatPrice(19.99);

This works because the second require_once does nothing.

If you used plain require twice, PHP would try to define formatPrice() twice and cause an error.

Example 4: Template usage

<?php
require_once 'config.php';
require_once 'database.php';

include 'header.php';
include 'sidebar.php';
include 'footer.php';

A common pattern is:

  • require_once for core setup files
  • include for reusable page fragments or templates

Step by Step Execution

Consider this example:

<?php
require_once 'functions.php';
include 'menu.php';
include 'menu.php';

echo sayHello();

Assume:

  • functions.php defines a function sayHello()
  • menu.php outputs some HTML menu

Step-by-step

Line 1

require_once 'functions.php';
  • PHP looks for functions.php
  • If found, PHP loads and runs it
  • PHP remembers that this file has already been included
  • If not found, PHP throws a fatal error and stops

Line 2

include 'menu.php';
  • PHP looks for menu.php
  • If found, PHP loads and runs it
  • If the file prints HTML, that output appears immediately
  • If not found, PHP gives a warning and continues

Line 3

include 'menu.php';
  • PHP loads menu.php again
  • Any HTML inside it is printed again
  • Any code in it runs again
  • If it defines a function or class, this may cause a redeclaration error

Line 4

echo sayHello();
  • PHP calls the function from functions.php
  • This works because the required file was loaded successfully

Key observation

  • include may run the same file multiple times
  • require_once guarantees one successful load or a fatal stop

Real World Use Cases

Common situations

Application bootstrap

require_once 'config.php';
require_once 'database.php';
require_once 'router.php';

These files are essential. If one is missing, the app cannot run correctly.

Shared utility functions

require_once 'helpers.php';

Helpers often define functions. Loading them more than once can cause redeclaration errors, so _once is appropriate.

Layout pieces

include 'header.php';
include 'footer.php';

Header and footer files are often treated as display pieces. In some projects they are still required, but many examples use include because they are template fragments.

Optional page sections

include 'special-offer.php';

If this file is missing, the page can still function without the optional section.

Legacy PHP applications

Older PHP apps often manually load many files. In that style, _once is commonly used for:

  • config files
  • shared libraries
  • class files
  • initialization logic
Take Quiz

Real Codebase Usage

In real codebases, developers usually choose based on criticality and safety.

Common pattern

<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/lib/database.php';
require_once __DIR__ . '/lib/helpers.php';

include __DIR__ . '/views/header.php';
include __DIR__ . '/views/page.php';
include __DIR__ . '/views/footer.php';

Why this pattern works

  • require_once is used for files the app depends on
  • include is used for view fragments that render output
  • __DIR__ makes file paths more reliable

Guarding critical startup code

Important setup code is often loaded early:

<?php
require_once __DIR__ . '/bootstrap.php';

If bootstrap fails to load, continuing would produce broken behavior, so stopping is correct.

Avoiding duplicate definitions

Files containing these items are often loaded with _once:

  • utility functions
  • constants
  • autoload setup
  • class definitions in older code

Error handling pattern

Although include only raises a warning, many modern codebases prefer to treat missing critical files as fatal. That makes failures obvious and easier to debug.

Modern note

In modern PHP projects using Composer autoloading, developers manually include fewer class files. But require and require_once are still commonly used for:

  • bootstrapping
  • config loading
  • entry points
  • small scripts and legacy apps

Common Mistakes

1. Using include for critical files

Broken example:

<?php
include 'database.php';
$db->query('SELECT 1');

If database.php is missing, the script may continue and then fail later with less clear errors.

Better:

<?php
require_once 'database.php';
$db->query('SELECT 1');

2. Including the same function file twice

Broken example:

<?php
require 'helpers.php';
require 'helpers.php';

If helpers.php defines functions, this can cause redeclaration errors.

Better:

<?php
require_once 'helpers.php';

3. Assuming _once means faster

_once is about correctness, not just performance. It prevents duplicates. Choose it when duplicate loading would be a problem.

4. Using include_once everywhere without thinking

This is not always wrong, but it can hide design decisions. Ask:

  • Is the file required?
  • Can the app continue without it?
  • Should it run once or multiple times?

5. Including files with fragile relative paths

Broken example:

<?php
require_once 'config.php';

This may fail depending on the current working directory.

Better:

<?php
require_once __DIR__ . '/config.php';

6. Including view files that accidentally define functions

Template files should usually render output only. If they also define functions or classes, repeated includes may create hard-to-find errors.

Comparisons

Quick comparison

StatementIf file is missingPrevents duplicate loading?Best used for
requireFatal error, script stopsNoMandatory files
includeWarning, script usually continuesNoOptional files
require_onceFatal error, script stopsYesMandatory files loaded one time
include_onceWarning, script usually continuesYesOptional files loaded one time

require vs include

Featurerequireinclude
File is essentialYesUsually no
Missing file behaviorFatal errorWarning
Script continues?NoUsually yes

_once vs non-_once

FeatureNon-_once_once
Loads same file againYesNo
Can repeat output/codeYesNo, if already loaded
Good for function/class filesRiskySafer

Practical rule of thumb

  • Use require_once for config, bootstrap, helpers, and dependency files
  • Use include for templates when repeated loading is acceptable
  • Use include_once only when the file is optional but should not be loaded twice
Take Quiz

Cheat Sheet

Syntax

require 'file.php';
include 'file.php';
require_once 'file.php';
include_once 'file.php';

Meaning

  • require = mandatory file
  • include = optional file
  • _once = only load one time

Missing file behavior

  • require / require_once -> fatal error, script stops
  • include / include_once -> warning, script may continue

Use this by default

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/helpers.php';
include __DIR__ . '/header.php';
include __DIR__ . '/footer.php';

Use _once when file defines

  • functions
  • classes
  • constants
  • initialization code

Avoid problems

  • Do not load function files twice with plain require
  • Do not use include for critical dependencies
  • Prefer __DIR__ for safer paths

Simple decision guide

  1. Is the file essential?
    • Yes -> use require
    • No -> use include
  2. Must it only be loaded once?
    • Yes -> use _once

That gives:

  • essential + once -> require_once
  • essential + repeat allowed -> require
  • optional + once -> include_once
  • optional + repeat allowed -> include

FAQ

What is the main difference between require and include in PHP?

require stops the script if the file cannot be loaded. include raises a warning and usually lets the script continue.

Should I use require_once by default in PHP?

For critical setup files like config, helpers, or bootstrap files, require_once is a safe default because it prevents duplicate loading.

When should I use include_once?

Use include_once when a file is optional but should not be loaded more than one time.

Can include load the same file multiple times?

Yes. Every include runs again unless you use include_once.

Why do duplicate includes cause errors?

If the included file defines functions, classes, or constants, loading it again may attempt to redefine them, which causes errors.

Is require_once always better than require?

Not always. If you intentionally want a file to run multiple times, use require. But for dependency files, require_once is often safer.

Do modern PHP frameworks still use these statements?

Yes, especially for bootstrapping and entry-point setup. However, class loading is often handled by Composer autoloading instead of manual includes.

Take Quiz

Mini Project

Description

Build a small PHP page that loads essential setup files and optional template files correctly. This project demonstrates how to choose between require_once and include, and how duplicate loading behaves in practice.

Goal

Create a simple PHP app entry file that safely loads configuration and helper code once, while rendering reusable page sections with includes.

Requirements

  • Create a config.php file that stores a site name variable.
  • Create a helpers.php file with one helper function.
  • Create header.php and footer.php template files.
  • In index.php, load the config and helpers safely, then include the header and footer.
  • Output a formatted message using the helper function and config value.
Take Quiz

Keep learning

Related questions

View more