PHP ยท Chapter 28 of 44

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.

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

Example 1 (php)
<?php
  // header.php
  echo "Site Header";
?>
Output
Site Header

This small file could be reused across many pages using include or require.

Example 2 (php)
<?php
  require_once "header.php";
  echo " - Page Content";
?>
Output
Site Header - Page Content

require_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.
๐Ÿ’ก Note: Using require_once for configuration and function files is a common best practice to avoid duplicate definitions.

๐Ÿ“ Quick Quiz

1. What happens if require cannot find the file?

2. What is the purpose of require_once?

3. Which is best used for a critical configuration file?