The include and require statements allow you to insert the content of one PHP file into another PHP file before the server executes it. This is perfect for creating reusable elements like navigation bars, headers, or footers.
Both statements are used similarly:
Imagine you have a website with 50 pages. Instead of writing the same HTML code for the menu on every page, you can write it once in a file named menu.php and include it like this:
If you want to change a link in the menu, you only need to update one file instead of 50.
The difference lies in how the script handles a failure (e.g., if the file is missing):
| Statement | Behavior on Error | Usage |
|---|---|---|
| include | Produces a Warning (E_WARNING) but the script continues to run. | Use for non-essential items like footers. |
| require | Produces a Fatal Error (E_COMPILE_ERROR) and the script stops immediately. | Use for essential items like database connections or security checks. |
If you accidentally include the same file twice, it might cause errors (like declaring the same function twice). To prevent this, use the _once version. It checks if the file has already been included; if so, it will not include it again.