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 vital for creating a modular structure and keeping your code **DRY** (Don't Repeat Yourself).
The main difference between include and require lies in how they handle a "missing file" error:
require if the file is critical to the application (like a database connection or config file). Use include for non-critical parts like a side banner or footer.
Imagine you have a common header file (header.php). You can include it in all your pages like this:
<?php
include 'header.php'; // Or require 'header.php';
echo "This is my main page content.";
?>
PHP also provides include_once and require_once. These functions check if the file has already been included/required earlier in the script. If it has, they won't include it again.
<?php
require_once 'config.php';
require_once 'config.php'; // This second line will be ignored
?>
require_once for files that define functions or classes to avoid "Cannot redeclare" errors.
header.php, footer.php, and sidebar.php in separate files so you only have to edit them once.config.php file.functions.php file.include $_GET['page'] . '.php'). This is a huge security vulnerability called **Local File Inclusion (LFI)**.
Now that you know how to organize your own files, let's learn how to manage external packages and libraries using the industry-standard tool: **PHP Composer & Autoloading**.