What are include and require in PHP?

Overview

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";
// or
include "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:

a.php included in b.php

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 and include are require_once and include_once. They behave like require and include except that they only require the file if it has not been included.

Example

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.

File structure

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.

How include helps avoid duplication

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";
A basic website with include

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";
A basic website with require

When we run this code, we'll get an error and the script will stop.

Summary

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.

Free Resources