PHP Include and Require Files

PHP include() & require() statement allow you to include PHP file within another PHP file. It including a file produces the same result as copying the script from the file specified and pasted into the location where it is called.

include () If file not found then return warning (E_WARNING) and the script will continue.

require() If file not found then return fatal error (E_COMPILE_ERROR) and stop the script.

Including files saves a lot of work. Also you can create a header, footer, or menu file for all your web pages.

The basic syntax of include() and require() statement

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

PHP include Examples

The following example will show you how to Include the common header, footer and menu codes which are stored in separate 'header.php', 'footer.php' and 'menu.php' files respectively, within all the pages of your website.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of include </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>

PHP require Examples

The following example will show you how to require the common header, footer and menu codes which are stored in separate 'header.php', 'footer.php' and 'menu.php' files respectively, within all the pages of your website.

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

PHP include vs require

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.

The include_once and require_once Statements

> include_once :- The include_once keyword is used to embed PHP code from another file. If the file is not found, a warning is shown and the program continues to run.

> require_once :- The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops.