Skip to content

/compare/php/include-vs-require

PHP include vs require vs require_once: what is the difference?

The commands on this page have not been executed by our verification runner yet.updated
tool
PHP
compares
include vs require

include and require both load and run another PHP file; they differ only when the file cannot be loaded. include emits a warning and the script continues, while require stops with a fatal error. The _once variants (include_once, require_once) do the same but skip the file if it was already loaded, which avoids "Cannot redeclare function" errors. Use require_once for files the program cannot run without (configuration, function libraries), include for optional parts such as templates, and Composer's autoloader for classes.

Differences

StatementFile missingAlready loaded
includeWarning, execution continues, returns falseLoaded and run again
include_onceWarning, execution continues, returns falseSkipped, returns true
requireFatal error, script stopsLoaded and run again
require_onceFatal error, script stopsSkipped, returns true

Example

php
<?php
require_once __DIR__ . '/config.php';     // must exist: stop if it is missing
require_once __DIR__ . '/vendor/autoload.php';

$settings = include __DIR__ . '/settings.local.php'; // a file can return a value
if ($settings === false) {
    $settings = [];                        // optional file: continue with defaults
}

include __DIR__ . '/templates/footer.php'; // optional part of the page

When the file is missing, include reports Warning: include(settings.local.php): Failed to open stream: No such file or directory and goes on; require reports the same warning followed by a fatal error, Failed opening required ..., and stops.

Notes

  • They are language constructs, not functions: require 'file.php'; and require('file.php'); are the same.
  • A bare file name ('lib.php') is searched in include_path, then in the calling script's directory and the current working directory; a path starting with ./ or ../ is relative to the current working directory only. Use __DIR__ . '/file.php' to make paths independent of where the script is started.
  • For classes, rely on autoloading (spl_autoload_register, or Composer's vendor/autoload.php) instead of one require_once per class.

Sources