PHP Include & Require files Tutorial

In this tutorial we learn how to break up our code into different files in PHP, and allow other files to access them by using include and require.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is include and require?

Applications can rapidly grow too large and out of control. Classes, namespaces and functions help us organize sections of our code into something more manageable.

Includes and requires help even further by separating sections of code into physical files.

Instead of having one giant file for the entire application, we can create smaller, more specific files that are included when and where we need them.

How to include a file

First, we will need a file to include:

  1. Open your IDE and navigate to your PHPProjects folder.
  2. In the Project Pane, right-click on the PHPProjects folder and select New File.
  3. Name the file main.php and press Enter or Return on your keyboard.
  4. Create another file, and name it file2.php

In the file2.php we will write a simple echo statement that will print a message to the screen.

Example: file2.php
<?php

echo "This text is included from file2.php";

?>

In the main.php file, we are going to include the contents of file2.php We do this with the include keyword, followed by the filename in between quotes.

Syntax:
 include 'filename.php';
Example: main.php
<?php

include "file2.php";

?>

When we run the main.php file in the browser, we can see that the echo statement in the file2.php is shown.

The interpreter took all the content from file2.php, copied it, and pasted it into main.php where the include statement is located. The following example will show exactly when the code from the included file becomes available.

Example: file2.php
<?php

$fruit = ["Apple", "Banana", "Pear"];

?>
Example: main.php
<?php

// $fruit does not exist, raise error
echo $fruit[0] . "<br>";

// Include file ith $fruit
include "file2.php";

// $fruit exists now, no error
echo $fruit[0] . "<br>";

?>

When we run main.php, we get the following output.

Output:
Notice: Undefined variable: fruit on line 4

Apple

The first line is an error, because at that point in the parsing of the script, the $fruit array didn’t exist.

Only after we include the file, does the $fruit array become accessible and we can print it to the page without error.

How to include a custom function

It’s time for a small challenge. Try to include and use the isEvenOdd() function from the Functions tutorial lesson, or any custom function you have in mind. If you get stuck, take a look at the code below.

Example: custom_math.php
<?php

function isEvenOdd($num) {
    if ($num % 2 == 0) {
        echo $num . " is an even number.<br>";
    } else {
        echo $num . " is an odd number.<br>";
    }
}

?>
Example: main.php
<?php

// Custom math functions
include "custom_math.php";

echo isEvenOdd(5);
echo isEvenOdd(10);

?>

How to require a file

When we require a file, it’s the same as including it.

When including a file that doesn’t exist, the interpreter will raise an error, but the rest of the script will still execute.

When we require a file that doesn’t exist, the interpreter will raise a fatal error, and the script will stop execution.

Syntax:
 require 'filename.php';
Example: file2.php
<?php

$fruit = ["Apple", "Banana", "Pear"];

?>
Example: main.php
<?php

require "file2.php";

foreach ($fruit as $item) {
    echo $item . "<br>";
}

echo "I print if an include fails, but not if a require fails."

?>

When we run the main.php file above, it’s executed as we would expect. If we delete the file however, the interpreter will raise a fatal error, and all execution will stop.

Output: missing file2.php
Warning: require(C:\xampp\htdocs\PHPProjects\file2.php): failed to open stream: No such file or directory on line 3

Fatal error: require(): Failed opening required 'file2.php' (include_path='C:\xampp\php\PEAR') on line 3

How to include_once or require_once

In some cases, a file may accidentally be included or required more than once. The interpreter would parse the file again, which would cause problems such as variable reassignments or function redefinitions.

PHP provides us with the include_once and require_once statements to help avoid such cases. When we use these, the interpreter will not include, or require, a file that has already been included or required.

Syntax: include_once
 include_once 'filename.php';
Syntax: require_once
 require_once 'filename.php';
Example:
<?php

if (include_once "file2.php") {
    echo "file2.php has already been included.<br>";
}

echo $fruit[0];

?>

Summary: Points to remember

  • Include and require allows us to separate our code into multiple files. By including or requiring a file, we have access to its content.
  • To include or require a file we simply write the keyword followed by the path of the file.
  • We can tell the interpreter to include or require a file only once, avoiding any accidental double inclusions.