include vs require vs include_once in PHP

Short answer

require raises a fatal error if the file is missing; include only emits a warning and carries on. Use require for anything your code cannot run without.

php
require 'config.php';        // fatal if missing — correct for essentials
include 'sidebar.php';       // warning if missing — page still renders

require_once 'functions.php';  // fatal, and only ever loaded once
include_once 'widget.php';

#Which to use

require for configuration, database connections, class definitions, function libraries. If the file is missing, continuing produces a cascade of confusing follow-on errors instead of one clear one.

include for optional presentation fragments where a missing file should degrade rather than break the page.

#The _once variants

They track what has already been loaded and skip repeats. Use require_once for anything that defines functions or classes — loading a file twice that contains function helper() {} is a fatal "cannot redeclare" error.

For plain templates, include is right; you may genuinely want the same fragment twice.

#Use absolute paths

Relative paths resolve against the including script's working directory, which changes depending on which file was requested:

php
require __DIR__ . '/config.php';

__DIR__ is the directory of the current file, always. This one habit prevents a whole category of "works locally, breaks on the server" bugs.

#Included files share scope

Variables defined before the include are visible inside it, and variables the include defines are visible after it. That is what makes templating work:

php
$title = 'Lessons';
include 'header.php';        // header.php can use $title

#In modern projects, use an autoloader

Composer's PSR-4 autoloader loads class files on demand, so you write require 'vendor/autoload.php' once and never think about it again.