← Back to Chapters

PHP Include and Require Statement

? PHP Include and Require Statement

? Quick Overview

The include and require statements in PHP are used to include and evaluate files within a script. These statements allow better code reusability by enabling a single PHP file to be reused across multiple scripts.

⚙️ Key Concepts

  • include – Generates a warning if the file is missing and continues execution.
  • require – Generates a fatal error if the file is missing and stops execution.
  • include_once – Includes a file only once.
  • require_once – Requires a file only once and stops execution if missing.

? Syntax / Theory

These statements are commonly used to load headers, footers, configuration files, database connections, and reusable logic.

? Example 1: Using include

? View Code Example
// Includes header.php and continues even if file is missing
<?php
include 'header.php';
echo "This is the body of the page.";
?>

? Explanation

The file header.php is inserted at runtime. If it does not exist, PHP shows a warning but executes the remaining script.

? Example 2: Using require

? View Code Example
// Requires config.php and stops execution if file is missing
<?php
require 'config.php';
echo "This is the body of the page.";
?>

? Explanation

If config.php is missing, PHP throws a fatal error and the script stops immediately.

? Example 3: Using include_once

? View Code Example
// Ensures header.php is included only once
<?php
include_once 'header.php';
include_once 'header.php';
echo "This is the body of the page.";
?>

? Explanation

Even though the statement appears twice, the file is included only once, preventing duplicate content.

? Example 4: Using require_once

? View Code Example
// Loads critical configuration file only once
<?php
require_once 'config.php';
require_once 'config.php';
echo "Configuration loaded successfully.";
?>

? Interactive Flow (Conceptual)

Request → PHP Script → include/require → External File → Output

This flow shows how PHP dynamically inserts external files before producing the final output.

? Use Cases

  • Including headers, footers, and navigation bars
  • Loading database connection files
  • Sharing configuration settings
  • Reusing utility functions across pages

✅ Tips & Best Practices

  • Use require for critical files like database configurations.
  • Use include for optional components.
  • Prefer require_once for files that must load only once.
  • Always verify correct file paths.

? Try It Yourself

  • Create a header file and include it using include.
  • Test script termination using require with a missing file.
  • Experiment with include_once to avoid duplicate content.
  • Use require_once for a database connection file.