As your website grows, writing the same code (e.g., menu or footer) on every single page becomes time-consuming and messy. The solution is file inclusion functions, which allow you to write code once and reuse it everywhere.
Include vs. Require: What is the difference?
Both functions do the same thing – they insert the content of another file into the current one. The only difference is what happens if the file cannot be found:
- include: Displays a Warning, but the script continues to run.
- require: Reports a Fatal Error and stops the script execution immediately.
Practical usage example
Instead of writing the entire HTML on every page, split the page into parts:
// index.php
include 'header.php';
include 'navbar.php';
echo "<h1>Welcome to my site!</h1>";
include 'footer.php';
When to use which?
Use require for critical files that the page cannot function without (e.g., database connection db.php or settings). For less critical parts, such as sidebars or widgets, you can use include.
With this approach, maintaining your website becomes incredibly easy – if you want to change the text in the footer, you only have to do it in one file!