As your website grows, writing the same code (e.g., menu or footer) on every page separately becomes time-consuming and hard to manage. The solution lies in file inclusion functions, which allow you to write code just once.
Include vs. Require: What's the difference?
Both functions do the same thing - they insert the content of another file into the current one. The difference lies only in what happens if the file cannot be found:
- include: Outputs a warning, but page execution continues.
- require: Throws a fatal error and immediately stops page execution.
Practical 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 essential files without which the site cannot function (e.g., database connection db.php
or settings). For less important parts, such as sidebars or extras, you can use include.
With this approach, maintaining your website will become child's play - if you want to change text in the footer, you only need to do it in one file!