PHP Include vs Include_once and Require vs Require_once

In PHP, managing how external files are loaded into your scripts is fundamental to building organized and reusable codebases. This article explains the critical differences between PHP’s four file inclusion statements—include, include_once, require, and require_once—focusing on how they handle error conditions and prevent duplicate file loading during script execution.

The “Once” Suffix: Preventing Duplicate Inclusions

The primary difference between the standard statements (include, require) and their “_once” counterparts (include_once, require_once) is how they handle multiple imports of the same file.

Example of the Duplicate Issue

Consider a file named functions.php:

<?php
function connectDatabase() {
    // Database connection logic
}

If you use standard include multiple times:

include 'functions.php';
include 'functions.php'; // This triggers a fatal error: Cannot redeclare connectDatabase()

If you use include_once:

include_once 'functions.php';
include_once 'functions.php'; // PHP ignores this second line; no error is thrown

Include vs. Require: Error Handling Differences

While the “_once” suffix controls how many times a file can be loaded, the choice between include and require determines what happens if the file is missing.

Statement Behavior if File is Missing Script Execution
include / include_once Emits a warning (E_WARNING) Continues running
require / require_once Emits a fatal error (E_COMPILE_ERROR) Stops immediately

Use include / include_once when:

The file is not essential to the core application logic. For example, loading a footer, sidebar, or tracking code where a failure to load should not break the entire webpage for the user.

Use require / require_once when:

The file is critical to the application’s functionality. For example, loading database configuration files, security helper functions, or core class definitions. If these files are missing, the script cannot run safely.


Summary of Use Cases