PHP Include
PHP Include and Require
Section titled “PHP Include and Require”The include and require statements allow you to insert the content of one PHP file into another. This is extremely useful for reusing code, such as headers, footers, configuration settings, or function libraries across multiple pages.
When a file is included, PHP effectively pauses execution of the current script, processes the included file, and then resumes execution in the original script.
include vs. require
Section titled “include vs. require”Both include and require achieve the same basic goal, but they differ in how they handle errors if the specified file cannot be found or read:
require: If the file is not found,requireproduces a fatalE_COMPILE_ERRORlevel error, halting the script execution immediately. Userequirefor essential files that your application cannot function without (e.g., database connections, core configuration, essential class definitions).include: If the file is not found,includeproduces a non-fatalE_WARNINGlevel error, and the script execution will attempt to continue (though likely with issues if the included file’s content was expected). Useincludefor optional files or when you want the script to try to proceed even if a piece is missing (e.g., including a template partial that might not always be present).
General Recommendation: In modern PHP development, especially when building structured applications, require (or require_once) is often preferred for critical dependencies to ensure the application fails fast if something essential is missing, preventing unexpected behavior later on.
include_once and require_once
Section titled “include_once and require_once”PHP also provides include_once and require_once. These statements behave identically to their counterparts (include and require) but with an added check: they ensure the specified file is included only once during the execution of a script. If the file has already been included, subsequent calls to include_once or require_once for the same file will be ignored.
This is crucial for preventing errors caused by redefining functions, classes, or constants that might occur if the same file were included multiple times.
Best Practice: Use require_once for including files containing definitions (like functions or classes) to prevent redeclaration errors. Use include_once if the inclusion is optional but should still only happen once.
Syntax
Section titled “Syntax”include 'path/to/filename.php';include_once 'path/to/filename.php';
require 'path/to/filename.php';require_once 'path/to/filename.php';
// Parentheses are optional but sometimes used// require_once('path/to/filename.php');The path to the file can be relative or absolute. PHP checks the include_path configuration directive to resolve relative paths.
PHP Include/Require Examples
Section titled “PHP Include/Require Examples”Example 1: Reusable Footer
Section titled “Example 1: Reusable Footer”Create a file named footer.php:
<?php// footer.php?><footer> <p>Copyright © 2000-<?= date('Y') ?> My Awesome Website. All rights reserved.</p></footer>Include this footer in your main page (index.php):
<!-- index.php --><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Welcome!</title></head><body>
<h1>Welcome to my home page!</h1><p>Some content goes here.</p><p>More content.</p>
<?php include 'footer.php'; // Or include_once ?>
</body></html>Example 2: Shared Configuration
Section titled “Example 2: Shared Configuration”Create a configuration file config.php (using require_once is safer here):
<?phpdefine('DATABASE_HOST', 'localhost');define('DATABASE_USER', 'webapp_user');define('DEBUG_MODE', false);
?>Use the configuration in another script:
<?php// db_connect.php
require_once 'config.php'; // Essential - script needs these constants
echo "Connecting to database host: " . DATABASE_HOST . "<br>";
if (DEBUG_MODE) { echo "Debug mode is ON.<br>";} else { echo "Debug mode is OFF.<br>";}
// ... proceed with database connection using constants ...
?>Example 3: Error Handling Difference
Section titled “Example 3: Error Handling Difference”Using include with a non-existent file:
<?php// script_using_include.phpecho "<h1>Welcome!</h1>";
include 'non_existent_file.php'; // Will generate a warning
echo "<p>This line might still be executed, despite the warning.</p>";?>Using require with a non-existent file:
<?php// script_using_require.phpecho "<h1>Welcome!</h1>";
require 'non_existent_file.php'; // Will generate a fatal error
// This line will NOT be executed because the script halts.echo "<p>This line will never be reached.</p>";?>Modern Alternatives: Autoloading
Section titled “Modern Alternatives: Autoloading”While require_once is still essential for procedural code or bootstrapping, modern PHP applications heavily rely on autoloading, especially for object-oriented programming. Autoloading automatically includes class files when they are first used, eliminating the need for long lists of require_once statements.
Tools like Composer manage dependencies and set up PSR-4 compliant autoloaders, which are the standard in contemporary PHP development. Understanding require/include is fundamental, but be aware that autoloading is the preferred method for managing class dependencies in larger projects.