How to Use PHP Include and Require Statements

In the realms of computer science and software engineering, reusability and modularity are considered to be important design principles to keep in mind when building software programs. The key idea behind these principles is to write code in a way that does not concentrate all it’s operations in one place. It is therefore advocated to break down your code into several smaller, atomic parts that are independent, reusable and replaceable. This makes projects easier to debug, reduces redundancy, saves an awful lot of memory and resources, and allows for localized, thus more stable updates.

image 1.png

A very common example of this can be seen in any website you visit on the internet. Most websites share a very common abstract structure - each webpage has a navigation bar (or header), a footer, and some content between the two. It is a common practice of web developers to reuse components like the header, footer, and many others across all the pages of the website. This can be implemented by defining these components once and using (importing/including) them anywhere and everywhere we like. 

The virtues of reusability and modularity are not just restricted to web components - we can just as effectively compartmentalize and reuse external classes, functions, and variables.

To be able to implement such a modular setting, we need to be able to include external files/modules into our code. Different programming languages use different ways to import modules. In this post, we will see how we can import files in our favorite web programming language, PHP.

We will learn to use PHP’s include and require functions to include external PHP files into our code. This will allow us to modularize our project and reuse existing blocks of PHP code without having to copy them to our main file. We will also look at two variants of these functions - include_once and require_once, and see how they can help us prevent likely errors. We’ll discuss plenty of examples to get a clear understanding of how these functions can be used. 

Here’s an outline of what we’ll be covering in this post so you can navigate the guide:

Let’s get started!

Include and Require Functions in PHP

Both, include and require functions in PHP that are used to import external files/modules into our code and evaluate them at the place where they have been imported. This is done by copying the contents from the external file into our main file during run-time.

image 2.png

Like we discussed above, being able to include files into our code allows us to systematically modularize and organize our project - to create separate files for separate components of our application and pull all of them into our code, wherever required. This also means that components created once can then be reused anywhere across our application, making it easier to maintain.

Let us look at both these functions in more detail.

Note: Throughout the rest of this post, the external file refers to the file that is to be included, and the main file refers to the file that is including the former.

PHP include

The include function takes as an argument the name of the file (string) to be included. You can invoke the function using either of the two ways -

include($filename);

or

include $filename;

When we import an external file into our code using the include function, the statements of the external file are executed at the line where include is called.

Now let’s look at some examples that use the include function.

PHP include Examples

We’ll start with a fairly basic example -

Example 1

Here, we’ll see how the code of an external file is executed from our main file upon inclusion.

We’ll do this by creating a file my_file.php and including it in an index.php file.

<?php
   // my_file.php
   echo "Called from my_file.php!<br>";
   $my_string = "Hello world!";
?>

Now we’ll include this file in our index.php file.

<!DOCTYPE html>
<!-- index.php -->
<html lang="en">
   <body>
       <?php
	    echo "Before file included.<br>";
          include 'my_file.php'; // including file
          echo $my_string;
       ?>
   </body>
</html>

OUTPUT

image 3.png

As you can see, the code from the included file (my_file.php) has been executed at the line where the file has been included.

Another thing to note here is that when you include an external file in your code, the variable scope of your main code (at the line where the include function is called) is merged with that of the included (external) file. Therefore, the variables, classes and functions accessible in the main file (where include is called) are also accessible in the external file. This also holds true vice versa i.e. variables declared in the external file are also accessible in your main code.

Example 2

Now let us look at an example where we can access and modify the state of our main code from an external file upon including it.

my_file.php (external file that we’ll include in index.php)

<?php
   // my_file.php
   echo "After file included -> <br>";
   $my_var += 5; // my_var is defined in index.php
  
?>

index.php

<!DOCTYPE html>
<!-- index.php -->
<html lang="en">
   <body>
       <?php
           echo "Before file included -> <br>";
           $my_var = 0; // declared a variable
           echo "initial value of my_var: ".$my_var."<br>";
           include 'my_file.php';
           echo "new value of my_var: ".$my_var."<br>";
       ?>
   </body>
</html>

OUTPUT

image 4.png

As we can see, the variable $my_var that was defined in index.php can be accessed (and modified) from our external file. This shows how the variable scope of the external file (my_file.php) is inherited by the main file (index.php). 

Example 3

Now let us look at a more extensive, practical example to understand how include can help us to reuse web components across a website. 

If we were to create a basic website, we would like to include a reusable navigation bar and a footer component that would be consistent across all pages. Let’s create a dummy website with an index web-page and a bunch of other (children) components that would serve as smaller reusable parts for our website. We can then include these in our index web-page. Let’s see how that works.

This is what we’ll want our web-page to look like.

Let’s first create the children components as such - nav.php, content.php, and footer.php.index.php web-page structure

nav.php (navigation bar)

<div class="nav">
   <nav>  <!-- using HTML nav tag for creating basic nav bar-->
       <a href="">Link 1</a> /
       <a href="">Link 2</a> /
       <a href="">Link 3</a> /
       <a href="">Link 4</a> /
   </nav>
</div>

content.php (arbitrary content)

<div class="content"> <!-- adding some basic content -->
   <h4> Content </h4>
   <p>
       Cupidatat excepteur ipsum nisi aute consequat.
   </p>
   <p>
       Sunt velit veniam exercitation tempor do id.
   </p>
</div>

footer.php

<div class="footer">
   <footer> <!-- using the HTML footer tag -->
       <div> I am a footer! </div>
   </footer>
</div>

Now that our children components are ready, let’s create the index.php file and add these to it. We’ll also add some very basic CSS styling for presentation purposes.

index.php

<!DOCTYPE html>
<html lang="en">
   <head>
       <style> /* adding some basic styling */
          
           .nav {
               background-color: lightblue; padding: 1%;
           }
          
           .content {
               background-color: lightgrey; padding: 1%;
           }
          
           .footer {
               background-color: darkseagreen; padding: 1%;
           }

       </style>
   </head>

   <body>
       <?php
	
           # defining names of files to be included here
           $nav_filename = 'nav.php';
           $content_filename = 'content.php';
           $footer_filename = 'footer.php';

           # including navigation bar here
           include $nav_filename;

           echo "<hr/>"; 
           
           # including content here
           include $content_filename;

           echo "<hr/>";

           # including footer here
           include $footer_filename;

       ?>
   </body>
</html>

OUTPUT:

image 5.png

As you can see, we were successfully able to include the various children's components into our main file. 

Similarly, these children's components (navbar, footer, and content) can be reused in all the different web-pages across the whole website. Because of this, as mentioned before, any prospective updates in either of these components will only have to be made in one place, instead of having to make changes in all the webpages that use these components.

This level of reusability and modularity makes for good coding practices and makes life much easier for web developers.

Now let us look at PHP’s similar require function.

PHP require

The require function works in the same way as include does, except for a small difference that we will discuss in the next section.

It also takes in the name of the file to be included as an argument - 

require($filename);

or

require $filename;

Let us look at how to require can be used through an example. 

PHP require Examples

In this example, we will inherit a function declared in an external file into our main file using require and then call it.

my_file.php

<?php
   function foo ($boo) { // function to be inherited by index.php
       echo "Function called!<br>";
       $boo += 5;
       return $boo;
   }
  
?>

index.php

<!DOCTYPE html>
<html lang="en">
   <body>
       <?php
           echo "Before file included.<br>";
           require 'my_file.php'; // this call inherits all the code from our external file
           $arg = 0;
           $boo = foo($arg); // calling the function
           echo "Function returned -> ".$boo;
       ?>
   </body>
</html>

OUTPUT:

IMAG 6.png

In the above example, we saw how we were able to execute a function defined in an external file from our main file.

Include vs Require

As you can see, include and require seem to be working in exactly the same way. There’s one important difference between the two though.

When calling the include function, if the path of the file to be included is invalid, then it emits a PHP warning (E_WARNING), and the rest of the code continues to execute.

On the other hand, if we call the required function and an invalid file path is provided, a PHP fatal error is raised and your code terminates right there. As a result, the remaining code is not executed.

Let us see this is in action through an example.

First, we’ll use the include function with an incorrect file path.

<!DOCTYPE html>
<!-- index.php -->
<html lang="en">
   <body>
       <?php
           echo "Before include function is called.<br>";
           include 'abc.php'; // incorrect file path provided
           echo "<br>✅ Remaining code continues to execute.";
       ?>
   </body>
</html>

OUTPUT:

IMAGE 7.png

As you can see, when we try to include an invalid file path, the code throws a warning, but still continues to execute the lines after that.

Note: Whether the warnings/error messages will be displayed or not depends on your system. Since error reporting is enabled on my system, warning messages are displayed in my output. In most cases however, error reporting is by-default disabled and in that case, your output might not include the warning or error message. In that case, your output might look like this - 

IMAGE 8.png

You can manually configure error reporting from your PHP code as shown below - 

error_reporting(0); // to disable error reporting
error_reporting(-1); // to enable error reporting

If you want to know more about error reporting in PHP, you can refer to our post on How to Enable PHP Error Reporting, where we talk about this in great detail. 

Coming back to the usage of include and require, now let’s look at how the to required function would behave when we provide an invalid file path.

We’ll use the same example as above and replace the include function with require.

<!DOCTYPE html>
<!-- index.php -->
<html lang="en">
   <body>
       <?php
           echo "Before include function is called.<br>";
           require 'abc.php'; // invalid file path provided
           echo "<br>✅ Remaining code continues to execute.";
       ?>
   </body>
</html>

OUTPUT:

image 9.png

As you can see, a fatal error message is raised and the code terminates at the line with the require statement - the remaining lines are not executed.

This is the main difference between how to include and to require work - include throws a warning, but allows the rest of the code to execute whereas require throws an error and exits your code immediately.

Include vs Require - Which one to use?

Since include does not interrupt execution, it might seem to be the better option. This can be true for small-scale personal projects where the stakes aren’t so high. However, for large-scale software systems, the counter-intuitive truth is that you would want your application to more strongly alert you about any potential inconsistency or inaccuracy in your code. 

Some include/require commands of your application that can be extremely critical to its normal functioning. Unnoticed warning messages (when using an include) lost in huge log files can manifest into a much bigger problem in the future if not accounted for. You’d rather let your code abruptly throw a fatal error once in a while than to let it affect your app’s functioning when it is released for production. It is important to embrace these errors and code-exits since they force you to be more aware of faults in your code and make debugging easier.

As an example, think of mistakenly using an incorrect path for your database configuration file in the code. If you use include, your invalid path warning might go unnoticed and all your database operations will suffer big time when your application goes into production. You are also likely to not know the reason for this problem because your code ran fine (it didn’t exit) and possibly the warnings were overlooked. You’ll have to spend quite some time debugging before you’d know about what the issue was and where it happened. 

A require statement would, therefore, be a better option in most such cases. The core idea is that even though errors are bad for users, they are quite essential for developers to take heed of inaccuracies in their code.

Preventing Errors: PHP Include_Once and Require_Once Statements

When you’re working on large projects, it is possible that occasionally you might by-mistake include the same PHP file in your code more than once. This can immediately lead to a fatal error if the file you happen to be including multiple times contains a function declaration or a class declaration.

Let’s look at an example to understand this better.

Here is the external file with a function that we wish to include - 

<?php
   // my_file.php
   echo "<b>Printing from inside the file!</b><br>";
   function foo ($boo) {
       echo "foo function called!<br>";
       $boo += 5;
       return $boo;
   }
  
?>

Now let’s see what happens if we include this file in our main file multiple times.

<!DOCTYPE html>
<!-- index.php -->
<html lang="en">
   <body>
       <?php
           echo "Before include function is called.<br>";
           include 'my_file.php'; // including the file once
           echo "File included once. Trying to include again!<br>";
           include 'my_file.php'; // trying to including it again
           echo "✅ It worked.";
          
       ?>
   </body>
</html>

OUTPUt

IMAGE 10.png

As you can see, a fatal error has been raised because when we include the file the second time, it tries to redeclare an existing function, which is not possible. 

Even if the included file does not contain a function, including multiple files once can sometimes be quite inefficient. 

To help us solve this problem, PHP provides include_once and require_once functions that can take care of multiple file inclusions. When you use these functions, they include any file only if it has not already been included before. Therefore, the inclusion will happen only once, regardless of the number of times the function is called.

Let us try this with an example-

We’ll try to include the same file that we saw in the previous example, but this time using the include_once function.

<!DOCTYPE html>
<!-- index.php -->
<html lang="en">
   <body>
       <?php
           echo "Before include function is called.<br>";
           include_once 'my_file.php'; // including the file once
           echo "File included once. Including again.<br>";
           include_once 'my_file.php'; // trying to including it again
           echo "✅ It worked.";
       ?>
   </body>
</html>

OUTPUT:

IMAGE 11.png

As we can see, this time our file wasn’t included the second time. We know this because the print statement from my_file.php was executed only once. As a result, the error wasn’t raised and our code didn’t exit mid-way.

The include_once and require_once functions also return a boolean value depending on whether the file has been included before or not.

The difference between include_once and require_once is the same as the difference between include and require. This means that  include_once will emit only a warning upon an invalid file path, whereas require_once will raise an error and halt code execution. Apart from that, both functions work exactly the same.

Concept Recap

In this post, we started by talking about the importance of writing modularized and reusable code. We learned about the include and require functions in PHP - about how they allow us to import other PHP files in our code. We saw how, despite the similarity, these functions significantly differ in the way they behave when an invalid file path argument is provided. We discussed the difference between the two and talked about how using to require might be a better option as compared to include. We also looked at the include_once and require_once functions - about how they check for multiple file inclusions and let you include any file only once. Throughout the post, we also looked at a bunch of examples to solidify our understanding of how these functions can be practically implemented.

Now that you know how to include files in your PHP code, go ahead and try to implement this in a personal project. You can start by creating a basic modular website that has different files for its different reusable web components like we did in one of the examples above. Then you could create a bunch of different web-pages that include (or require) these children components. You could also create a utility class file with some functions that can be used by each of your website’s pages.

Stay healthy, stay safe, and keep learning! Happy coding!

Did you find this article helpful or see something you disagree with or think should be improved? Please let us know, we value your feedback!