In building any website, you frequently need to use the same block of code on multiple pages—think of a standard header, footer, navigation bar, or database connection file. PHP provides four core statements to insert the content of one PHP file into another, promoting code reusability and modularity.
1. The Four Code Inclusion Statements
PHP offers two pairs of statements: include / require and include_once / require_once. The difference between the pairs lies in how they handle errors and redundancy.
| Statement | Error Handling | Purpose and Usage |
include | Generates a Warning (E_WARNING) if the file is not found, but the script will continue execution. | Use for non-critical files like footers or non-essential HTML components. |
require | Generates a Fatal Error (E_COMPILE_ERROR) if the file is not found, and the script will halt immediately. | Use for critical files like database connection settings, configuration files, or core classes. |
include_once | Same error handling as include. | Ensures the file is included only once, even if the statement is called multiple times. |
require_once | Same error handling as require. | Ensures the file is required only once. Recommended for functions, class definitions, and critical files. |
2. When to Use Which Statement
Best Practice: Always use the _once variants to prevent functions and classes from being defined multiple times, which would result in fatal errors.
- Use
require_oncefor files essential to your application’s function (e.g.,db_config.php,User.phpclass definition). - Use
include_oncefor files that are non-critical but might appear conditionally (e.g., a special promotional banner).
3. Practical Example: Structuring a Page
Imagine a website where every page needs a common header and footer.
File: header.php
<!DOCTYPE html>
<html>
<head>
<title>My Awesome Site</title>
</head>
<body>
<div id="navigation">Home | About | Contact</div>
<div id="content">
File: footer.php
</div> <div id="footer">
© <?php echo date("Y"); ?> My Awesome Site
</div>
</body>
</html>
File: index.php (The Main Page)
<?php
// Use require_once for stability (if the header is missing, the page is broken)
require_once 'header.php';
?>
<h2>Welcome to the Homepage</h2>
<p>This is the main content of the site.</p>
<?php
require_once 'footer.php';
?>
4. File Paths and Safety
When using inclusion statements, be cautious about file paths.
- Relative Paths: Paths are resolved relative to the file being executed, not the file where the
includestatement is written. This can lead to issues. - Absolute Paths: To ensure stability, it’s best to use absolute paths based on the server’s root.
The __DIR__ magic constant (or __FILE__) is highly recommended for building safe, absolute paths that work across different servers:
<?php
// Safely require the config file located in a 'config' subdirectory
// regardless of which script is currently running:
require_once __DIR__ . '/config/app_config.php';
?>
