Back to course

Including Files: include vs. require

PHP: The Complete 0 to Hero Bootcamp

10. Including Files: include vs. require

As applications grow, we must organize code into separate files (e.g., headers, footers, configuration). PHP offers four ways to include external files.

Why Include Files?

  • Modularity: Separating concerns (e.g., database connection in config.php).
  • Reusability: Using the same header/footer across many pages.
  • Maintainability: Easier to update one file than many.

1. include

The include statement reads the specified file and executes the code within it. If the file is not found, it issues a Warning and the script continues to run.

php

Welcome to the main content!"; include 'footer.php'; ?>

2. require

The require statement is identical to include, except when the file is not found. If the file is missing, it issues a Fatal Error and stops the script execution immediately.

php

Rule of Thumb: Use require for essential files (like config or function definitions) and include for non-essential parts (like templates or optional components).

3. include_once and require_once

These variants ensure that the file is included and executed only once, even if the statement is called multiple times. This prevents function re-declaration errors and variable conflicts.

php