PHP Include & Require
include and require let you insert the content of one PHP file into another, which is great for reusing code such as headers, footers, or shared functions across multiple pages.
The difference is how they handle missing files: include produces a warning and continues execution, while require produces a fatal error and stops the script. Both also have '_once' variants that prevent the same file from being included multiple times.
include "file.php";
require "file.php";
require_once "config.php";include vs require
Use require for essential files your script cannot run without, like a database configuration file. Use include for optional files, like an ad banner, where a missing file shouldn't crash the whole page.
include_once and require_once
These variants check whether the file has already been included and skip it if so, preventing issues like redefining the same function or class twice.
<?php
// header.php
echo "Site Header";
?>Site HeaderThis small file could be reused across many pages using include or require.
<?php
require_once "header.php";
echo " - Page Content";
?>Site Header - Page Contentrequire_once inserts header.php's output once, then the rest of the script continues.
Key points
- include and require both insert another PHP file's content.
- require stops the script with a fatal error if the file is missing; include just warns.
- The _once variants prevent a file from being included more than once.
- Use require for critical files and include for optional ones.
