The require Function
The require
function includes and executes the specified file in the current script. Unlike include
, if the file is missing, it causes a fatal error and stops script execution. The function is often used to include important files with functions, classes, or settings.
Syntax
require 'path/to/file.php';
Example
Including a configuration file:
<?php
require 'config.php';
echo $db_host; // Variable from config.php
?>
If the config.php
file exists, its contents will be executed, and the variables will become available.
Example
Attempting to include a non-existent file:
<?php
require 'missing_file.php';
echo 'This line will not execute';
?>
If the missing_file.php
file does not exist, the script will terminate with an error.
Difference Between require and include
The main difference is that require
causes a fatal error if the file is missing, whereas include
only issues a warning.
<?php
include 'optional_file.php'; // The script will continue to work
require 'required_file.php'; // The script will stop on error
?>
See Also
-
the
include
function,
which also includes files but does not stop the script on error -
the
require_once
function,
which guarantees that the file is included only once