What is the Difference Between include and require in PHP
In PHP, both include
and require
are used to include and evaluated files, but there is a key difference in how they handle errors.
1. include:
If the file is not found or there is an error while including it, PHP will emit a warning and continue the script execution.
include('non_existent_file.php'); // Will give a warning, but the script will continue running
2. require:
If the file is not found or there is an error while including it, PHP will emit a fatal error and stop script execution immediately.
require('non_existent_file.php'); // Will give a fatal error and stop script execution.
In general:
Use include
when the file is optional and the script can continue running without it.
Use require
when the file is essential for the script to work and the script should stop if it’s missing.
Both function also have _once
variants (include_once
and require_once
), which ensure the file is included only once, even if the statement is called multiple times.