PHP allows you to include other files with the .php extension using four different statements:
Each of these four statements does almost the exact same thing, with a few slight differences in functionality. We'll go over each of these statements in this tutorial.
To include a PHP file, use either of the four statements with the following syntax:
Although not required, you could alter the syntax by wrapping parenthesis around your file names:
include statement simply loads the contents of another PHP file. If the file does not exist, a warning message will display on the screen, but the remainder of the script will process regularly.
include_once statement works the same as
include except it checks if the same script is loaded multiple times. If the same script is loaded again after its initial load, it will ignore subsequent includes of the same script.
require statement works similarly to
include in that it loads a specific PHP script that you pass it. The difference is that the script will throw an error and stop processing immediately if the included PHP script file does not exist.
require_once statement will stop processing the PHP script if the file doesn't exist on the server, but it will also only include and process a PHP file once if it's included multiple times throughout your script.
Include Path Examples
There are several ways you can include PHP files. You can use relative paths, where the script included is in the same directory as the running script:
You can include scripts within a subdirectory:
You can also include scripts using absolute paths:
This tutorial covered four ways of including other PHP files throughout your script, each with use cases and examples.