How to Use PHP Include and Require Statements

09/04/2021

Contents

In this article, you will learn how to use PHP include and require statements.

PHP Include and Require Statements

The include and require statements in PHP are used to include the contents of one PHP file into another.

The include statement will include the specified file and continue execution of the script even if the file is not found or fails to execute.

The require statement works similarly, but it will generate a fatal error and stop the execution of the script if the file is not found or fails to execute.

To use these statements, simply include the path to the file you want to include in the statement. For example:

<?php
  include 'file1.php';
  require 'file2.php';
?>

It’s recommended to use require_once or include_once instead of require or include to avoid redeclaring same variables or functions.

<?php
  include_once 'file1.php';
  require_once 'file2.php';
?>

If the file you want to include is in a different directory, you will need to specify the path to that directory. For example:

<?php
  include 'path/to/directory/file1.php';
  require 'path/to/directory/file2.php';
?>
 

In addition to including files, the include and require statements can also be used to include the output of a PHP script. This can be useful for creating modular and reusable code.

For example, if you have a file called header.php that contains the HTML code for the header of your website, you can use the include or require statement to include that file in multiple pages, rather than duplicating the code on each page.

You can also pass variables to the included file by simply assigning a value to a variable before the inclusion statement, and then using the variable in the included file.

For example, in the parent file:

<?php
  $title = "My Website";
  include 'header.php';
?>

And in the header.php

<title><?php echo $title; ?></title>

In this way, you can use the include and require statements to create modular, reusable code that can be easily maintained and updated.

It’s also worth noting that the include and require statements can be nested, meaning that an included file can also include or require other files. However, care should be taken to avoid creating an include loop, where a file includes another file that includes the first file, resulting in an infinite loop.