File Inclusion in PHP (With Program Examples)

In PHP, there are two functions that are used to put the contents of a file containing PHP source code into another PHP file, and these are include and require.

What is File Inclusion in PHP?

PHP File Inclusion lets us use the code in one PHP file in another PHP file.

Including a file has the same effect as copying the script from the file specified and pasting it into the place where it is called.

What are two types of file inclusion?

There are two PHP functions for including one PHP file within another PHP file.

  1. The include() Function
  1. The require() Function

The include() Function

The include() function replicates the whole contents of a specified file into the file that uses the include() function.

If there is a problem loading a file, the include() function generates a warning, but script execution continues.

Syntax:

include('filename');

Example:

Assume that we want to create a standard menu for our website. Then, create a menu.php file containing the following text.

<a href="https://itsourcecode.com/">Home</a> - 
<a href="https://itsourcecode.com/free-projects/">Projects</a> - 
<a href="https://itsourcecode.com/contact-us/">Contact Us</a> - 
<a href="https://itsourcecode.com/about-us/">About</a> <br />
<hr>

Include the menu.php in as many pages as wishes to create a header. For example, our test.php file can now contain the following code.

<html>
<body>

<?php
include('menu.php');
?>
<p>The code above shows how to include a file in another php file.</p>

</body>
</html>

It will result in the following output:

To execute the script, enter “localhost/[FolderName]/test.php” in the address bar of the web browser.

php include output

The require() Function

The require() function inserts the entire content of a specified file into the file that uses the include function.

If there is a problem loading a file, the require() function throws a fatal error and stops the script from running.

In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue. Based on PHP Official Documentation.

Syntax:

require('filename');

The only difference between include() and require() is how they handle error conditions.

It is recommended to use the require() function rather than the include() function, as scripts should not continue to execute if files are missing or misnamed.

Example:

Using the require() function with the preceding example will produce the same result. However, if we try the two examples below where the file does not exist, we will obtain different results.

For the include() function:

<html>
<body>

<?php
include('menu123.php');
?>
<p>The code above shows an error if you include a file in another PHP file with an incorrect file name.</p>

</body>
</html>

It will result in the following output:

PHP Warning:  include(menu123.php): Failed to open stream: No such file or directory in C:\xampp\htdocs\phptuts\test.php on line 5
PHP Warning:  include(): Failed opening 'menu123.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\phptuts\test.php on line 5
The code above shows an error if you include a file in another PHP file with an incorrect file name.

For the require() function:

<html>
<body>

<?php
require('menu123.php');
?>
<p>The code above shows an error if you include a file using require in another PHP file with an incorrect file name.</p>

</body>
</html>

This time, an error will occur, and no output will be seen.

PHP Warning:  require(menu123.php): Failed to open stream: No such file or directory in C:\xampp\htdocs\phptuts\test.php on line 5
PHP Fatal error:  Uncaught Error: Failed opening required 'menu123.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\phptuts\test.php on line 5
Stack trace:
#0 {main}
  thrown in C:\xampp\htdocs\phptuts\test.php on line 5

Take note that we might just get simple warnings, fatal error messages, or nothing at all. This depends on how we set up our PHP Server.

PHP include and require Statements

The include/require statement copies all text, code, and markup from the specified file into the file that contains the include() statement.

When we wish to include the same PHP, HTML, or text on several pages of a website, including files is quite beneficial.

With the include or require statement, it is possible to insert the contents of one PHP file into another PHP file (before the server runs it).

The include and require statements are exactly the same, except for what happens if they both fail:

  • require will prompt a fatal error (E_COMPILE_ERROR) and stop the script from executing.
  • include will only prompt a warning (E_WARNING), and the script will keep executing.

Use the include statement if you want the execution to continue and the output to be displayed even if the include file is missing.

In the case of FrameWork, CMS, or complicated PHP applications, the require statement must always be used to include a crucial file in the execution flow.

This will prevent your application’s security and integrity from being compromised in the event that a crucial file is mistakenly deleted.

Including files reduces work significantly.

This allows you to build a standard header, footer, or menu file for your entire website. Then, when the header has to be updated, only the included header file needs to be modified.

More Examples

Example 1:

Let us say we have a “footer.php” file with a standard footer that looks like this:

<hr>
<?php
echo "<p>Copyright &copy; 2020-" . date("Y") . " ITSC</p>";
?>

Use the include statement to add the footer file to a page:

<html>
<body>

<h1>This is PHP File Inclusion</h1>
<p>Some text.</p>
<p>Some more text.</p>
<p>Some more text.</p>

<?php
include('footer.php');
?>

</body>
</html>

Example 2:

Based on the above example, we are going to add a standard menu file called “menu.php“:

<a href="https://itsourcecode.com/">Home</a> - 
<a href="https://itsourcecode.com/free-projects/">Projects</a> - 
<a href="https://itsourcecode.com/contact-us/">Contact Us</a> - 
<a href="https://itsourcecode.com/about-us/">About</a> <br />
<hr>

This menu file should be used on every page on the site. Here’s how to do it (we are using a <div> element so that we can style the menu easily with CSS later):

<html>
<body>

<div class="menu">
<?php
include('menu.php');
?>
</div>

<h1>This is PHP File Inclusion</h1>
<p>Some text.</p>
<p>Some more text.</p>
<p>Some more text.</p>


<div class="footer">
<?php
include('footer.php');
?>
</div>

</body>
</html>

Example 3:

Let us say we have a file called “vars.php” that contains some variables:

<?php
$name='Prince Ly';
$number='29';
?>

The variables can then be used in the calling file if the “vars.php” file is included:

<html>
<body>

<h1>This is PHP File Inclusion</h1>

<?php
include('vars.php');
echo "Hi, my name is $name and my favorite number is $number.";
?>

</body>
</html>

Example 4

Let us say we have a file called “functions.php” that contains some functions:

<?php
function sayHi($name) {
    echo "Hi, my name is $name!";
}
?>

And it is used in another PHP script, test.php.

<html>
<body>

<?php
require ('functions.php');
sayHi("Prince");
echo "\n";

// initializing it again
require ('functions.php');
sayHi("Grace");
?>

</body>
</html>

To prevent this, use require_once. Even if asked to include the file again, the include once and require once statements will only include it once, i.e. if the file was already included in a prior statement, it is not included again.

<html>
<body>

<?php
require_once('functions.php');
sayHi("Prince");

echo "<br>";

require_once('functions.php');
sayHi("Grace");
?>

</body>
</html>

Summary

In summary, file inclusion in PHP lets us use the code in one PHP file in another PHP file. There are two types of file inclusion: include() and require().

Additionally, both the include() statement and the require() statement are identical, but the difference between the two is how they handle their error message.

It is preferred to use the require() statement because of its ability to stop the file from executing.

Lastly, if you want to learn more about File Inclusion in PHP, please leave a comment below. We’ll be happy to hear it!

Leave a Comment