Include and Require in PHP
Introduction
In PHP, the include and require statements are used to include the content of one PHP file into another PHP file before the server executes it. This is especially useful for reusing code, such as headers, footers, or any other common elements across multiple pages.
Using include
The include statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. If the file is not found, include will emit a warning (E_WARNING) but the script will continue execution.
Example of using include:
<?php
include 'header.php';
echo "Welcome to my home page!";
?>
Using require
The require statement is identical to include, except upon failure it will also produce a fatal error (E_COMPILE_ERROR) and stop the script. In other words, it will halt the execution of the script if the file to be included is not found.
Example of using require:
<?php
require 'header.php';
echo "Welcome to my home page!";
?>
Difference between include and require
The key difference between include and require is how they handle errors:
- include: Emits a warning, but the script will continue execution.
- require: Emits a fatal error, and the script will stop execution.
Example of include with a missing file:
<?php
include 'missingfile.php';
echo "This line will be executed even if the file is missing.";
?>
Warning: include(missingfile.php): failed to open stream: No such file or directory in ...
This line will be executed even if the file is missing.
Example of require with a missing file:
<?php
require 'missingfile.php';
echo "This line will not be executed if the file is missing.";
?>
Fatal error: require(): Failed opening required 'missingfile.php' ...
Best Practices
Here are some best practices when using include and require:
- Use require when the file is essential to the application (e.g., configuration files).
- Use include when the file is not critical, and the application can still run if the file is missing (e.g., optional templates).
- Always use the absolute path for including files to avoid path issues.
- Use include_once and require_once to prevent multiple inclusions of the same file.
Example of include_once:
<?php
include_once 'header.php';
include_once 'header.php'; // This will not include the file again
?>