HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP include & require

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 Difference

The main difference between include and require lies in how they handle a "missing file" error:

  • include: Will produce a Warning (E_WARNING) but the script will continue to run.
  • require: Will produce a Fatal Error (E_COMPILE_ERROR) and the script will stop immediately.
Rule of Thumb: Use 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.

Using include and require

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.";
?>

The _once Versions

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
?>
Tip: Always use require_once for files that define functions or classes to avoid "Cannot redeclare" errors.

Practical Use Cases

  • Layouts: Keep your header.php, footer.php, and sidebar.php in separate files so you only have to edit them once.
  • Configurations: Store your database credentials and API keys in a config.php file.
  • Helper Functions: Put all your common functions in a functions.php file.

Summary

  • include: Continues on error (Warning).
  • require: Stops on error (Fatal Error).
  • _once: Prevents multiple inclusions of the same file.
  • Files are included based on their path (Relative or Absolute).
Security Tip: Never include files based on user input (e.g., include $_GET['page'] . '.php'). This is a huge security vulnerability called **Local File Inclusion (LFI)**.

What's Next?

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**.