Explain PHP Include Files with example
PHP include files are a way to reuse code across multiple PHP files. This practice helps in maintaining code consistency and makes it easier to manage large applications by breaking down code into smaller, reusable components.
How include
and require
Work
PHP provides two main functions for including files:
include
require
Both functions do the same thing: they include and evaluate the specified file. The difference is in how they handle errors:
include
will produce a warning but the script will continue execution if the file is not found.require
will produce a fatal error and stop the script if the file is not found.
Example 1: Using include
main.php
<?php
include 'header.php';
echo "<p>This is the main content of the page.</p>";
include 'footer.php';
?>
header.php
<?php
echo "<h1>Welcome to My Website</h1>";
?>
footer.php
<?php
echo "<footer>© 2024 My Website</footer>";
?>
Output of main.php
<h1>Welcome to My Website</h1>
<p>This is the main content of the page.</p>
<footer>© 2024 My Website</footer>
Example 2: Using require
main.php
<?php
require 'header.php';
echo "<p>This is the main content of the page.</p>";
require 'footer.php';
?>
If header.php
or footer.php
is missing, main.php
will produce a fatal error and stop execution.
Handling Missing Files
main.php with include
<?php
include 'nonexistent.php'; // This will produce a warning but continue execution
echo "<p>This is the main content of the page.</p>";
?>
Output
Warning: include(nonexistent.php): failed to open stream: No such file or directory in /path/to/main.php on line 2
Warning: include(): Failed opening 'nonexistent.php' for inclusion (include_path='.:/usr/share/php') in /path/to/main.php on line 2
<p>This is the main content of the page.</p>
main.php with require
<?php
require 'nonexistent.php'; // This will produce a fatal error and stop execution
echo "<p>This is the main content of the page.</p>";
?>
Output
Fatal error: require(): Failed opening required 'nonexistent.php' (include_path='.:/usr/share/php') in /path/to/main.php on line 2
Using include_once
and require_once
These functions ensure that a file is included only once during the script execution, avoiding issues with multiple inclusions.
main.php
<?php
include_once 'header.php';
include_once 'header.php'; // This will not include header.php again
echo "<p>This is the main content of the page.</p>";
?>
Conclusion
Using include
, require
, include_once
, and require_once
helps in managing large codebases by breaking down the code into smaller, reusable components. It also makes the code easier to maintain and debug.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.