In PHP, to include one file in another, we use either include
or require
.
Both include
and require
are used to include files in another file. They're very useful when building a website because they help to avoid code duplication.
The syntax looks like this:
require "path/to/file";// orinclude "path/to/file";
include
and require
copy the content of the required file in the exact place they are required. This is how b.php
is created:
When include
is used, the script will continue to run even if the file is missing. There will be a warning in the program. However, when require
is used, the program generates a fatal error, meaning that the script stops running when the file cannot be found. As a result, we prefer to use require
for important inclusions like database configuration, environment variables, and so on.
Note: Other variants for
require
andinclude
arerequire_once
andinclude_once
. They behave likerequire
andinclude
except that they only require the file if it has not been included.
Let's build a basic website to see how these control structures can help.
First, let's see the project files structure of the site we want to build.
Our project directory is called "educative" and it contains three files, as well as one folder in the root. The "includes" folder contains two files.
Now, let's see how include
will help us build this site.
<?php /** * @author Abel L Mbula */ include "includes/header.php"; echo "<h1>Contact</h1>"; echo "<p>educative@educative.io</p>"; include "includes/footer.php";
Let's look at an example of require
where a file is missing.
<?php /** * @author Abel L Mbula */ include "includes/header.php"; echo "<h1>Contact</h1>"; echo "<p>educative@educative.io</p>"; include "includes/footer.php";
When we run this code, we'll get an error and the script will stop.
include
and require
are similar, except that they handle errors differently. include
generates a warning if an error occurs, but the script will continue execution. require
, on the other hand, generates a fatal error, and causes the script to stop.