PHP

PHP Menu

PHP

Include Files - PHP Advance

You may save a significant amount of time and effort by incorporating files — Instead of entering the full block of code numerous times, save it in a separate file and include it anywhere you want using the include() and require() instructions. A common example is including the header, footer, and menu files on all of a website's pages.

The include and require statements are identical, except upon failure:

  • require will produce a fatal error (E_COMPILE_ERROR), stop the script
  • include will only produce a warning (E_WARNING), the script will continue

The syntax of the include() and require() statement are as follows:

include 'path/to/file.php';

or

require 'path/to/file.php';

Examples

Assume there is a standard header file called header.php as follows:

<?php
    
echo "<p>Welcome to PHP Tutorials</p>";

To include the header file in a page, the include statement is used:

<html>
<body>
    <h1>PHP Tutorial Page!</h1>
    <p>Some text.</p>
    <p>Some more text.</p>
    <?php include 'header.php';?>
</body>
</html>

The include_once and require_once Statements

It is possible that conflicts will arise if you include the same file (usually function or class files) more than once within your code using include or require commands. PHP includes include_once and require_once statements to avoid this issue. With one exception, these statements function similarly to include and require statements.

Below is an example of the require_once statement. Supposing the code below is in the file hello.php:

<?php

function sayHello($x) {
    echo "Hello, $var!";
}

And it is included in another php script, main.php

<?php

// Including file
require "hello.php";
// Calling the function
sayHello("Mark"); // Output: Hello, Mark!
echo "<br>";
             
// Including file once again
require "hello.php";
// Calling the function
sayHello("Jeff"); // Doesn't execute

To avoid this, require_once can be used. Even if asked to include the file again, the include_once and require_once statements will only include it once, i.e., if the specified file has already been included in a previous statement, the file is not included again.

<?php

// Including file
require_once  "hello.php";
// Calling the function
sayHello("Mark"); // Output: Hello, Mark!
echo "<br>";
             
// Including file once again
require_once  "hello.php";
// Calling the function
sayHello("Jeff"); // Output: Hello, Jeff!

Introduction

PHP Basics

PHP Advance

PHP OOP

PHP Functions and Methods