PHP Include and Require

In this chapter we will study PHP include and require functions:

Problem: As we all know, PHP allows us to develop a variety of functions and elements that can be reused across multiple pages. Scripting the same function across numerous pages takes a lot of time and work.

Solution: File inclusion is the solution. It allows us to combine many files, such as text or codes, into a single program, saving time and effort or to code multiple times.

There are two functions that assist us in file inclusion:

  • PHP include() Function
  • PHP require() Function

File inclusion helps in the creation of functions, headers, footers, and other components that can be reused across multiple pages. It helps the developer to change the layout of the website by simply altering the included file.

PHP include() Function

The include() function copies all of the text from a given file into the file that calls the include function. The include() function generates a warning if there is difficulty loading a file, but the script will still run.

Syntax

include 'filename';

Lets discuss an exapmle in which we will create a common menu file for our website and will include it in our website page home.php:

Menu.php

<a href="#">Home</a> - 
<a href="#">About us</a> - 
<a href="#">Contact us</a> - 

Now you may make as many pages as you want and use this file . Lets include it in our website page home.php:

<html>
   <body>
   
      <?php include 'menu.php'; ?>
      <p>This is an example to show how to include PHP file!</p>
      
   </body>
</html>

PHP require() Function

The require() function puts all of the text from a given file into the file that contains the require function. The require() function generates a fatal error and stops the script’s execution if there is difficulty loading a file.

Syntax

require 'filename';

Lets include same above menu.php file in our website page home.php using require function

<html>
   <body>
   
      <?php require 'menu.php'; ?>
      <p>This is an example to show how to include PHP file using require!</p>
      
   </body>
</html>

include() VS require():

So, aside from how they handle error scenarios, require() and include() are identical. Because in case of require function scripts will not continue to execute if files are missing or misnamed, so it is better to use include function.