What is the difference between include, include_once, require, and require_once?

In PHP, the four statements – include, include_once, require, and require_once – are used to incorporate the contents of one file into another file. However, they have distinct differences:

1. include

The include statement includes the specified file. If the file is not found, it will emit a warning but the script will continue to execute.

2. include_once

The include_once statement behaves like include, but it will check if the file has already been included, avoiding duplicate inclusions.

3. require

The require statement is similar to include, but if the file is not found, it will produce a fatal error, stopping the script execution.

4. require_once

The require_once statement is like require, but it also ensures that the file is only included once, preventing duplicate includes and fatal errors.

Example Usage


// Example of include
include 'header.php'; // Continues execution if header.php is not found

// Example of include_once
include_once 'header.php'; // Prevents duplicates

// Example of require
require 'config.php'; // Fatal error if config.php is not found

// Example of require_once
require_once 'functions.php'; // Ensures functions.php is included only once
    

keywords: include include_once require require_once PHP file inclusion