PHP Include and Require Files

In this tutorial you will learn how to include and evaluate the files in PHP.

Including a PHP File into Another PHP File

The include() and require() statement allow you to include the code contained in a PHP file within another PHP file. Including a file produces the same result as copying the script from the file specified and pasted into the location where it is called.

You can save a lot of time and work through including files — Just store a block of code in a seperate file and include it whereever you want by include() and require() statement instead of typing the entire block of code multiple times. A typicall example is including the header, footer and menu file in all the pages of a website.

The basic syntax of the include() and require() statement can be given with:

include("path/to/filename"); -Or- include "path/to/filename";
require("path/to/filename"); -Or- require "path/to/filename";
 

Tip:Like the print and echo statements, you can omit the parentheses while using the include and require statements as demonstrated above.

The following example will show you how to include the common header, footer and menu code which is stored in a separate 'header.php', 'footer.php' and 'menu.php' files respectively within all the pages of your website. Using this technique you can update all pages of the website at once by making the changes to just one file.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  •     <title>Tutorial Republic</title>
  • </head>
  • <body>
  • <?php include "header.php"; ?>
  • <?php include "menu.php"; ?>
  •     <h1>Welcome to Our Website!</h1>
  •     <p>Here you will find lots of useful information.</p>
  • <?php include "footer.php"; ?>
  • </body>
  • </html>

Difference Between Include and Require Statements

You might be thinking if we can include files using the include() statement then why we need require(). Typically the require() statement operates like include().

The only difference is — the include() statement will only generate a PHP warning but allow script execution to continue if the file to be included can't be found, whereas the require() statement will generate a fatal error and stops the script execution.

  • <?php require "my_variables.php"; ?>
  • <?php require "my_functions.php"; ?>
  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  •     <title><?php displayTitle($home_page); ?></title>
  • </head>
  • <body>
  • <?php include "header.php"; ?>
  • <?php include "menu.php"; ?>
  •     <h1>Welcome to Our Website!</h1>
  •     <p>Here you will find lots of useful information.</p>
  • <?php include "footer.php"; ?>
  • </body>
  • </html>
 

Tip:It is recommended to use the require() statement if you're including the library files or files containing the functions and configuration variables that are essential for running your application.

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.