← Back to Chapters

PHP include_once & require_once

? PHP include_once & require_once

? Quick Overview

The include_once and require_once statements in PHP work similarly to the include and require statements. The key difference is that these functions ensure the specified file is included only once, regardless of how many times the statement is called in the script.

⚙️ Key Concepts

  • include_once – Includes the file only once. If the file has already been included, it will not be included again.
  • require_once – Includes the file only once, but stops script execution if the file cannot be found.

? Syntax / Theory

Both statements prevent duplicate file loading, which helps avoid function redeclaration errors and repeated variable definitions.

? Code Example 1: include_once

? View Code Example
// Including header.php only once even if called multiple times
<?php
include_once 'header.php';
include_once 'header.php';
echo "This is the body of the page.";
?>

? Live Output / Explanation

The file header.php is included only once, preventing duplicate HTML output or PHP errors.

? Code Example 2: require_once

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

? Live Output / Explanation

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

? Interactive / Practical Example

? View Code Example
// Loading reusable functions safely with require_once
<?php
require_once 'functions.php';
require_once 'functions.php';
greetUser("Meghraj");
?>

? Use Cases

  • Loading configuration files
  • Including database connection scripts
  • Using shared utility or helper functions
  • Preventing duplicate class or function declarations

✅ Tips & Best Practices

  • Use require_once for mandatory files like configs.
  • Use include_once for optional components.
  • Always verify correct file paths.

? Try It Yourself

  • Create a PHP page using require_once for a missing file and observe the error.
  • Include a footer file multiple times using include_once.
  • Test redeclaration errors by removing _once and comparing behavior.