Advertisement
Google Ad Slot: content-top
PHP Include Files
PHP include Statement
The include statement in PHP is used to include the content of one PHP file into another PHP file. It allows you to reuse code across multiple pages, making your applications more modular and easier to maintain.
The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.
Syntax:
include 'filename.php';
How it Works:
- When the
includestatement is executed, PHP will insert the contents of the specified file at the point where theincludestatement appears in the script. - The
filename.phpcan be a relative or absolute path.
PHP include Examples
Assume we have a standard footer file called "index.php", that looks like this:
Assume we have a standard footer file called "header.php", that looks like this:
Assume we have a standard footer file called "footer.php", that looks like this:
In this example:
- The
header.phpfile is included at the top ofindex.phpto display the header. - The
footer.phpfile is included at the bottom ofindex.phpto display the footer.
Differences Between include and require:
include: Will generate a warning (E_WARNING) if the file is not found but the script will continue executing.require: Will generate a fatal error (E_COMPILE_ERROR) and stop the script execution if the file is not found.
If we do the same example using the require statement, the echo statement will not be executed because the script execution dies after the require statement returned a fatal error:
Note
Use require when the file is required by the application.
Use include when the file is not required and application should continue when file is not found.